返回

如何在 Qt 中实现网页历史记录和查找功能

后端

实现网页历史记录功能

为了实现网页历史记录功能,我们需要创建一个 QWebEngineHistory 对象。该对象提供了用于管理历史记录的 API,包括添加、删除和获取历史记录项。

QWebEngineHistory *history = view->history();

接下来,我们需要创建一个 QPushButton 对象,当用户点击该按钮时,将添加当前网页到历史记录中。

QPushButton *backButton = new QPushButton(this);
backButton->setText("后退");

然后,我们将 QPushButton 对象的 clicked() 信号连接到 QWebEngineHistory 的 addToHistory() 方法。这样,当用户点击该按钮时,当前网页将被添加到历史记录中。

connect(backButton, &QPushButton::clicked, history, &QWebEngineHistory::addToHistory);

最后,我们需要创建一个 QComboBox 对象,当用户选择一个历史记录项时,将加载该项对应的网页。

QComboBox *historyComboBox = new QComboBox(this);

然后,我们将 QComboBox 对象的 currentTextChanged() 信号连接到 QWebEngineView 的 load() 方法。这样,当用户选择一个历史记录项时,该项对应的网页将被加载到 QWebEngineView 中。

connect(historyComboBox, &QComboBox::currentTextChanged, view, &QWebEngineView::load);

实现网页查找功能

为了实现网页查找功能,我们需要创建一个 QLineEdit 对象,当用户在该文本框中输入搜索词时,将查找该词在网页中的所有匹配项。

QLineEdit *lineEdit = new QLineEdit(this);

然后,我们将 QLineEdit 对象的 textChanged() 信号连接到 QWebEngineView 的 findText() 方法。这样,当用户在文本框中输入搜索词时,该词将在网页中被查找。

connect(lineEdit, &QLineEdit::textChanged, view, &QWebEngineView::findText);

最后,我们需要创建一个 QPushButton 对象,当用户点击该按钮时,将查找下一个匹配项。

QPushButton *findNextButton = new QPushButton(this);
findNextButton->setText("查找下一个");

然后,我们将 QPushButton 对象的 clicked() 信号连接到 QWebEngineView 的 findNext() 方法。这样,当用户点击该按钮时,下一个匹配项将在网页中被查找。

connect(findNextButton, &QPushButton::clicked, view, &QWebEngineView::findNext);

结论

通过使用 QWebEngineHistory 和 QWebEngineView 类,我们成功地实现了网页历史记录和查找功能。这些功能使我们的网络浏览器更具用户友好性,并为用户提供了更好的网页浏览体验。