Evgenii Legotckoi
Evgenii LegotckoiDec. 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 .

#-------------------------------------------------
#
# Project created by QtCreator 2015-12-18T20:10:57
#
#-------------------------------------------------

QT       += core gui webkit webkitwidgets

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = QWebViewExample
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

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.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtWebKitWidgets/QWebView>
#include <QUrl>
#include <QDebug>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

private slots:
    void slotEnter();       
    void slotLinkClicked(QUrl url); 
};

#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().

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Set the manual handling of click on link
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    // Connect the signal pressing "Enter" in the field qlineEdit
    connect(ui->lineEdit, &QLineEdit::returnPressed, this, &MainWindow::slotEnter);
    // Connect the signal click on the link to the handler
    connect(ui->webView, &QWebView::linkClicked, this, &MainWindow::slotLinkClicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotEnter()
{
    // Load the page specified in the URL field lineEdit
    ui->webView->load(QUrl(ui->lineEdit->text()));
}

void MainWindow::slotLinkClicked(QUrl url)
{
    // Clicking on the link put the address in the field qlineEdit
    ui->lineEdit->setText(url.toString());
    ui->webView->load(url);     // Загружаем страницу по этой ссылке
}

Correction of errors with SSL

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

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

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

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 файле

QT       += core gui webkit webkitwidgets

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

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

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

QT += webenginewidgets

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

Сделал так

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

void Compilyator::on_pushButton_2_clicked()
{
    ui->preview->load(QUrl("https://ideone.com/"));
    ui->preview->show();

}
Михаиллл
  • 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
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 7:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 3:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 5:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks