Evgenii Legotckoi
Dec. 18, 2015, 10:30 p.m.

Qt/C++ - Lesson 036. QWebView – How to make simple browser on the Qt

Note: The lesson is deprecated. With version Qt5.6 must use WebEngine

Well, who among us does not want to write your browser? Come on, do not deny it thought about the browser exactly were. So, the Qt has QWebView class that allows you to work with webkit browser engine, which is written chromium, and, accordingly, chrome and many other browsers. Therefore, practical use of a dozen lines of code, you can make an application that can display a page of the website.

Thus, the application will be as follows. There is an address bar QLineEdit and a widget QWebView . When you enter a website address in the address bar and pressing Enter key will start getting the site and display it in QWebView . When you click on the link in the link address will be displayed in the address bar and a new page will be loaded in the widget.

Project structure for work with QWebView

  • QWebViewExample.pro - the profile of the project;
  • main.cpp - the main project source code file;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - file source code of the main application window;
  • mainwindow.ui - form the main application window.

QWebViewExample.pro

To work with QWebView need to connect two modules: webkit and webkitwidgets .

  1. #-------------------------------------------------
  2. #
  3. # Project created by QtCreator 2015-12-18T20:10:57
  4. #
  5. #-------------------------------------------------
  6.  
  7. QT += core gui webkit webkitwidgets
  8.  
  9. greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
  10.  
  11. TARGET = QWebViewExample
  12. TEMPLATE = app
  13.  
  14.  
  15. SOURCES += main.cpp\
  16. mainwindow.cpp
  17.  
  18. HEADERS += mainwindow.h
  19.  
  20. FORMS += mainwindow.ui

mainwindow.h

The header must declare two slots:

slotEnter() - for the handling of pressing the Enter key in the browser address bar;
slotLinkClicked(QUrl url) - to handle a click on a link on the browser page.

Также необходимо подключить библиотеки QWebView и QUrl.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QtWebKitWidgets/QWebView>
  6. #include <QUrl>
  7. #include <QDebug>
  8.  
  9. namespace Ui {
  10. class MainWindow;
  11. }
  12.  
  13. class MainWindow : public QMainWindow
  14. {
  15. Q_OBJECT
  16.  
  17. public:
  18. explicit MainWindow(QWidget *parent = 0);
  19. ~MainWindow();
  20.  
  21. private:
  22. Ui::MainWindow *ui;
  23.  
  24. private slots:
  25. void slotEnter();
  26. void slotLinkClicked(QUrl url);
  27. };
  28.  
  29. #endif // MAINWINDOW_H

mainwindow.cpp

For handling correctlry of a click on the link you need to install the manual processing of the event by setLinkDelegationPolicy and connect the appropriate slot to the signal linkClickek().

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. ui->setupUi(this);
  9.  
  10. // Set the manual handling of click on link
  11. ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
  12.  
  13. // Connect the signal pressing "Enter" in the field qlineEdit
  14. connect(ui->lineEdit, &QLineEdit::returnPressed, this, &MainWindow::slotEnter);
  15. // Connect the signal click on the link to the handler
  16. connect(ui->webView, &QWebView::linkClicked, this, &MainWindow::slotLinkClicked);
  17. }
  18.  
  19. MainWindow::~MainWindow()
  20. {
  21. delete ui;
  22. }
  23.  
  24. void MainWindow::slotEnter()
  25. {
  26. // Load the page specified in the URL field lineEdit
  27. ui->webView->load(QUrl(ui->lineEdit->text()));
  28. }
  29.  
  30. void MainWindow::slotLinkClicked(QUrl url)
  31. {
  32. // Clicking on the link put the address in the field qlineEdit
  33. ui->lineEdit->setText(url.toString());
  34. ui->webView->load(url); // Загружаем страницу по этой ссылке
  35. }

Correction of errors with SSL

Chances are you have an error that resembles the following when you build the project:

  1. qt.network.ssl: QSslSocket: cannot call unresolved function SSLv23_client_method
  2. qt.network.ssl: QSslSocket: cannot call unresolved function SSL_CTX_new
  3. qt.network.ssl: QSslSocket: cannot call unresolved function SSL_library_init
  4. qt.network.ssl: QSslSocket: cannot call unresolved function ERR_get_error

The solution to this problem lies in the fact, to throw the necessary libraries to the folder where are Qt5Network.dll and Qt5Networkd.dll library. These libraries are libeay32.dll and ssleay32.dll .

For this:

  1. Go to the following site
  2. We are looking for light build of OpenSSL
  3. And shakes the required version of 32 or 64 bits (in the case of mingw swing 32-bit assembly).
  4. Next install OpenSSL in derivative folder item noting "The OpenSSL binaries (\ bin) directory"
  5. Then we look for the libraries libeay32.dll and ssleay32.dll and we move them to a folder with the Qt libraries Qt5Network.dll and Qt5Networkd.dll.

Result

As a result of the work done, you can open a page of the site in its own application, as shown in the following figure.

Link to the project download in zip-archive: qwebviewexample.zip

Video

Do you like it? Share on social networks!

D
  • Feb. 17, 2017, 3:01 a.m.

qt.network.ssl: QSslSocket: cannot call unresolved function SSLv23_client_method
qt.network.ssl: QSslSocket: cannot call unresolved function SSL_CTX_new
qt.network.ssl: QSslSocket: cannot call unresolved function SSL_library_init
qt.network.ssl: QSslSocket: cannot call unresolved function ERR_get_error

А если этот метод не помог,как быть?

Evgenii Legotckoi
  • Feb. 17, 2017, 10:13 a.m.

Возможно, библиотеки не подошли. Либо попытаться подключить непосредственно в проект. Там на сайте должна быть dev версия вместе с заголовочными файлами. Вот эту версию в проект и подключать тогда.

Михаиллл
  • Feb. 7, 2019, 3:53 p.m.

Записал в .pro файле

  1. QT += core gui webkit webkitwidgets

не находит это и выдает ошибку:Unknown module(s) in QT: webkit webkitwidgets
скажите пожалуйста, почему так

Evgenii Legotckoi
  • Feb. 7, 2019, 3:58 p.m.

Статья устарела, используйте QWebEngine

  1. QT += webenginewidgets

Михаиллл
  • Feb. 7, 2019, 4:55 p.m.
  • (edited)

Сделал так

  1. QT += core gui webenginewidgets

Выдает туже ошибку: Unknown module(s) in QT: webenginewidgets

Михаиллл
  • Feb. 7, 2019, 4:55 p.m.

Компилятор MinGW 64 5.12

Evgenii Legotckoi
  • Feb. 7, 2019, 5:09 p.m.

Переходить на MSVC, ибо MinGW не поддерживается.

Михаиллл
  • Feb. 7, 2019, 5:32 p.m.

Компилятор MSVC 2015 64bit тоже выдает ту-же ошибку

Evgenii Legotckoi
  • Feb. 7, 2019, 5:36 p.m.

А вот это уже странно. Перезапуск qmake делали? webengine установлен? Он идёт отдельным пунктом в Maintanence Tool

Михаиллл
  • Feb. 7, 2019, 7:11 p.m.

Проверил, Qt WebeEgine установлен. Запускал qmake.

Михаиллл
  • Feb. 7, 2019, 7:12 p.m.

На этом компе глюки с QML, может в этом дело?

Evgenii Legotckoi
  • Feb. 8, 2019, 12:09 p.m.

Не думаю. Мне надо будет самому тогда проверить, как получится, отпишусь.

RL
  • Feb. 10, 2019, 2:55 a.m.
  • (edited)

тоже проблемма Unknown module(s) in QT: webenginewidgets

Как быть ?

у меня Desktop Qt %{Qt:Version} clang 64bit -> на этом не покатит ? !

Михаиллл
  • Feb. 11, 2019, 4:49 p.m.

Была ли у вас возможность проверить WebeEgine?

Evgenii Legotckoi
  • Feb. 11, 2019, 4:51 p.m.

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.

Михаиллл
  • Feb. 11, 2019, 8:39 p.m.

Не повезло вам.

М
  • March 27, 2019, 5:17 p.m.

Проверьте пожалуйста QT += webenginewidgets и # include < QtWebEngineWidgets>

o
  • July 11, 2019, 9:27 p.m.
  • (edited)

+

v
  • Jan. 13, 2020, 11:39 p.m.

Такая же проблема Unknown module(s) in QT: webenginewidgets на Qt5.12.3 + VS2015
Оказалось, что 2015-й не поддерживает webenginewidgets, а с MSVC 2017 - работает!

s
  • June 4, 2020, 1 a.m.

Вроде вск записала правильно, все подключила . Проблем со сборко нет.
НО вместо сайта выводится белый экран просто. В чем проблема может быть?

По задумке, при нажатии на кнопку должен выводится сайт в qwebengineview

  1. void Compilyator::on_pushButton_2_clicked()
  2. {
  3. ui->preview->load(QUrl("https://ideone.com/"));
  4. ui->preview->show();
  5.  
  6. }
Михаиллл
  • June 4, 2020, 1:25 a.m.

Если взяли все из примера, то не должно собраться, т.к. webkit webkitwidgets уже не работают.
Какой класс Вы используете для браузера?

s
  • June 4, 2020, 1:32 a.m.

я с учетом обновлений использовала webenginewidgets

s
  • June 4, 2020, 1:33 a.m.

я с учетом обновлений использовала webenginewidgets

Михаиллл
  • June 4, 2020, 1:50 a.m.

И использовали QWebEngineView как виджет?
Попробуйте setUrl(const QUrl &url)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup