English Български

Open Web Page in QWebView

The following tutorial shows how to load a web page using QUrl [doc.qt.nokia.com] in QWebView [doc.qt.nokia.com] . QWebView is a widget provided by WebKit in Qt [doc.qt.nokia.com] that is used to view and edit web documents.

  • Specify that you want to link against the QtWebkit module by adding this line to your qmake .pro file:

  1. QT += webkit

  • Include required headers

  1. #include <QWebView>
  2. #include <QUrl>

  • Create instance of QWebView

  1. m_pWebView = new QWebView(this);
  2. //set position and size
  3. m_pWebView->setGeometry(0,0,200,200);

Additionally QWebView style can be customized using setStyleSheet().

  • Load a web page

  1. m_pWebView->load(QUrl("http://www.example.com"));

Example

This example has been built with Qt SDK 1.1 and tested on Symbian^3 devices.

mainwindow.h

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QtGui/QMainWindow>
  5. #include <QWebView>
  6. #include <QUrl>
  7.  
  8. namespace Ui {
  9.     class MainWindow;
  10. }
  11.  
  12. class MainWindow : public QMainWindow
  13. {
  14.     Q_OBJECT
  15. public:
  16.  
  17.     explicit MainWindow(QWidget *parent = 0);
  18.     virtual ~MainWindow();
  19.  
  20. private:
  21.  
  22.     QWebView* m_pWebView;
  23. };
  24.  
  25. #endif // MAINWINDOW_H

mainwindow.cpp

  1. #include "mainwindow.h"
  2.  
  3. #include <QtCore/QCoreApplication>
  4.  
  5. MainWindow::MainWindow(QWidget *parent)
  6.     : QMainWindow(parent)
  7. {
  8.     m_pWebView = new QWebView(this);
  9.     //set position and size
  10.     m_pWebView->setGeometry(0,0,200,200);
  11.     m_pWebView->load(QUrl("http://www.example.com"));
  12. }
  13.  
  14. MainWindow::~MainWindow()
  15. {
  16.  
  17. }

main.cpp

  1. #include "mainwindow.h"
  2.  
  3. #include <QtGui/QApplication>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     QApplication app(argc, argv);
  8.  
  9.     MainWindow mainWindow;
  10.     mainWindow.showMaximized();
  11.     return app.exec();
  12. }

Troubleshooting

  • QWebView: No such file or directory

Make sure you have added webkit to the .pro file of the project.

  1. QT += webkit

See also

Embed YouTube Video in QWebView [developer.qt.nokia.com]
Extending QtWebKit [developer.qt.nokia.com]

Categories:

  • Tutorial
  • HowTo
  • snippets
  •