Window Class Implementation
Since the layout of the user interface is provided by the window.ui user interface file, we only need to call the setupUi() in the constructor:
Window::Window(QWidget *parent)
: QWidget(parent)
{
setupUi(this);
}
This adds all the controls to the window and sets up connections between their signals and suitably-named slots in the Window class. The QLineEdit instance was given a name of elementLineEdit in Qt Designer, so the on_elementLineEdit_returnPressed() slot is automatically connected to its returnPressed() signal.
This slot performs the main work of this example. We begin by obtaining a QWebFrame instance for the current page shown in the QWebView widget. Each QWebFrame contains a QWebElement instance that represents the document, and we obtain this in order to examine its contents:
void Window::on_elementLineEdit_returnPressed()
{
QWebFrame *frame = webView->page()->mainFrame();
QWebElement document = frame->documentElement();
QWebElementCollection elements = document.findAll(elementLineEdit->text());
foreach (QWebElement element, elements)
element.setAttribute("style", "background-color: #f0f090");
}
Taking the contents of the QLineEdit as the query text, we call the element's findAll() function to obtain a list of elements that match the query.
For each element obtained, we modify its style by setting its style attribute to give it a yellow background color.
Since we also want the query to be performed when the user clicks the Highlight button, we also implement the on_highlightButton_clicked() slot to simply call the on_elementLineEdit_returnPressed() slot when it is invoked:
void Window::on_highlightButton_clicked()
{
on_elementLineEdit_returnPressed();
}
For completeness, we also implement a setUrl() function which simply passes on a QUrl instance to the equivalent function in the QWebView widget:
void Window::setUrl(const QUrl &url)
{
webView->setUrl(url);
}
Starting the Example
The main function implementation is simple. We set up the application, create a Window instance, set its URL, and show it:
#include <QtGui>
#include "window.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Window window;
window.setUrl(QUrl("http:));
window.show();
return app.exec();
}
When the application's event loop is run, the WebKit home page will load, and the user can then begin to start running queries against the contents of the page. The highlighting can only be removed by reloading the page. To do this, open a context menu over the page and select the Reload menu item.
Further Reading
The QWebElement documentation contains more information about DOM access for the QtWebKit classes.
In this example, we take advantage of Qt's auto-connection feature to avoid explicitly connecting signals to slots.