Qt Reference Documentation

Contents

Simple Web Plugin Example

Files:

The Simple Web Plugin example shows how to embed a regular Qt widget into a Web page displayed using QWebView.

[Missing image webkit-simplewebplugin.png]

In this example, we will show how to include Qt widgets in Web-centric user interfaces.

QtWebKit Basics

QtWebKit provides integration between Qt and WebKit on two different levels. On a low level, Qt provides widgets for Web pages to be rendered onto; on a high level, a set of classes are provided that represent all the key components of a Web browser.

QWebView is a widget that is used to display Web pages, QWebPage represents the content in a page, and QWebFrame represents an individual frame in a Web page. The code to display a Web page is very simple:

     QWebView *view = new QWebView(parent);
     view->load(QUrl("http://qt.nokia.com/"));
     view->show();

The widget provides fundamental Web browsing features, such as Cascading Style Sheet and JavaScript support. Other technologies can be added to provide a more comprehensive experience.

Adding a Widget to a Page

Since Qt is used to render pages, it is easy to add both standard and custom widgets to pages. All we need is some markup to indicate where a widget is expected in a page and a mechanism that lets us know when it needs to be created.

The markup used involves the <object> element, described in the HTML 4 specification, which is used to include generic objects in Web pages. When describing an object to represent a widget, there are typically three attributes this element can have: a data attribute that indicates where any relevant data can be obtained; width and height attributes can be used to set the size of the widget on the page.

Here's how we might describe such an object:

 <object type="text/csv;header=present;charset=utf8"
         data="qrc:/data/accounts.csv"
         width="100%" height="300"></object>

The mechanism used by QtWebKit to insert widgets into pages is a plugin factory that is registered with a given WebPage instance. Factories are subclasses of QWebPluginFactory and can be equipped to supply more than one type of widget.

Creating a Widget to Embed

To demonstrate how the factory is used, we create a simple widget that can be used to display Comma-Separated Values (CSV) files. The widget class, CSVView, is just a subclass of QTableView with extra functions to set up an internal data model. Instances of the factory class, CSVFactory, are responsible for creating CSVView widgets and requesting data on their behalf.

The CSVFactory class is defined in the following way:

 class CSVFactory : public QWebPluginFactory
 {
     Q_OBJECT

 public:
     CSVFactory(QObject *parent = 0);
     QObject *create(const QString &mimeType, const QUrl &url,
                     const QStringList &argumentNames,
                     const QStringList &argumentValues) const;
     QList<QWebPluginFactory::Plugin> plugins() const;

 private:
     QNetworkAccessManager *manager;
 };

The public functions give a good overview of how QtWebKit will use the factory to create widgets. We begin by looking at the factory's constructor:

 CSVFactory::CSVFactory(QObject *parent)
     : QWebPluginFactory(parent)
 {
     manager = new QNetworkAccessManager(this);
 };

The factory contains a network access manager which we will use to obtain data for each of the plugin widgets created.

The plugins() function is used to report information about the kinds of widget plugins it can create; our implementation reports the MIME type it expects and provides a description of the plugin:

 QList<QWebPluginFactory::Plugin> CSVFactory::plugins() const
 {
     QWebPluginFactory::MimeType mimeType;
     mimeType.name = "text/csv";
     mimeType.description = "Comma-separated values";
     mimeType.fileExtensions = QStringList() << "csv";

     QWebPluginFactory::Plugin plugin;
     plugin.name = "CSV file viewer";
     plugin.description = "A CSV file Web plugin.";
     plugin.mimeTypes = QList<MimeType>() << mimeType;

     return QList<QWebPluginFactory::Plugin>() << plugin;
 }

The create() function is where most of the action happens. It is called with a MIME type that describes the kind of data to be displayed, a URL that refers to the data, and information about any additional arguments that were specified in the Web page. We begin by checking the basic MIME type information passed in the mimeType parameter, and only continue if we recognize it.

 QObject *CSVFactory::create(const QString &mimeType, const QUrl &url,
                             const QStringList &argumentNames,
                             const QStringList &argumentValues) const
 {
     if (mimeType != "text/csv")
         return 0;

     CSVView *view = new CSVView(argumentValues[argumentNames.indexOf("type")]);

We construct a view widget using the fully-specified MIME type, which is guaranteed to be in the list of arguments if a MIME type has been supplied.

     QNetworkRequest request(url);
     QNetworkReply *reply = manager->get(request);
     connect(reply, SIGNAL(finished()), view, SLOT(updateModel()));
     connect(reply, SIGNAL(finished()), reply, SLOT(deleteLater()));

     return view;
 }

Lastly, we use the network access manager to request the data specified by the url parameter, connecting its finished() signal to the view's updateModel() slot so that it can collect the data. The reply object is intentionally created on the heap; the finished() signal is connected to its deleteLater() slot, ensuring that Qt will dispose of it when it is no longer needed.

The CSVView class provides only minor extensions to the functionality of QTableView, with a public slot to handle incoming data and a private variable to record exact MIME type information:

 class CSVView : public QTableView
 {
     Q_OBJECT

 public:
     CSVView(const QString &mimeType, QWidget *parent = 0);

 public slots:
     void updateModel();

 private:
     void addRow(bool firstLine, QStandardItemModel *model,
                 const QList<QStandardItem *> &items);

     QString mimeType;
 };

The constructor is simply used to record the MIME type of the data:

 CSVView::CSVView(const QString &mimeType, QWidget *parent)
     : QTableView(parent)
 {
     this->mimeType = mimeType;
 }

To save space, we will only look at parts of the updateModel() function, which begins by obtaining the QNetworkReply object that caused the slot to be invoked before checking for errors:

 void CSVView::updateModel()
 {
     QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

     if (reply->error() != QNetworkReply::NoError)
         return;

     bool hasHeader = false;
     QString charset = "latin1";

Assuming that the data is correct, we need to determine whether the CSV file includes a table header, and to find out which character encoding was used to store the data. Both these pieces of information may be included in the complete MIME type information, so we parse this before continuing---this is shown in the online example code.

     QTextStream stream(reply);
     stream.setCodec(QTextCodec::codecForName(charset.toLatin1()));

     QStandardItemModel *model = new QStandardItemModel(this);

Since QNetworkReply is a QIODevice subclass, the reply can be read using a suitably configured text stream, and the data fed into a standard model. The mechanics of this can be found in the code listing. Here, we skip to the end of the function where we close the reply object and set the model on the view:

     reply->close();

     setModel(model);
     resizeColumnsToContents();
     horizontalHeader()->setStretchLastSection(true);
 }

Once the reply has been read, and the model populated with data, very little needs to be done by the plugin. Ownership of the view widget is handled elsewhere, and we have ensured that the model will be destroyed when it is no longer needed by making it a child object of the view.

Let's look quickly at the MainWindow implementation:

 MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent)
 {
     QWebSettings::globalSettings()->setAttribute(
         QWebSettings::PluginsEnabled, true);

     QWebView *webView = new QWebView;
     CSVFactory *factory = new CSVFactory(this);
     webView->page()->setPluginFactory(factory);
     QFile file(":/pages/index.html");
     file.open(QFile::ReadOnly);
     webView->setHtml(file.readAll());

     setCentralWidget(webView);
     setWindowTitle(tr("Simple Web Plugin Example"));
 }

Apart from creating and setting a factory on the QWebPage object, the most important task is to enable Web plugins. If this global setting is not enabled, plugins will not be used and our <object> elements will simply be ignored.

Further Reading

The Web Plugin Example extends this example by adding a signal-slot connection between the embedded widget and a JavaScript function in the page.