Evgenii Legotckoi
Evgenii LegotckoiDec. 18, 2015, 11:30 a.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. 16, 2017, 4:01 p.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. 16, 2017, 11:13 p.m.

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

Михаиллл
  • Feb. 7, 2019, 4:53 a.m.

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

QT       += core gui webkit webkitwidgets

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

Evgenii Legotckoi
  • Feb. 7, 2019, 4:58 a.m.

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

QT += webenginewidgets

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

Сделал так

QT       += core gui webenginewidgets

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

Михаиллл
  • Feb. 7, 2019, 5:55 a.m.

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

Evgenii Legotckoi
  • Feb. 7, 2019, 6:09 a.m.

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

Михаиллл
  • Feb. 7, 2019, 6:32 a.m.

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

Evgenii Legotckoi
  • Feb. 7, 2019, 6:36 a.m.

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

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

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

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

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

Evgenii Legotckoi
  • Feb. 8, 2019, 1:09 a.m.

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

RL
  • Feb. 9, 2019, 3:55 p.m.
  • (edited)

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

Как быть ?

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

Михаиллл
  • Feb. 11, 2019, 5:49 a.m.

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

Evgenii Legotckoi
  • Feb. 11, 2019, 5:51 a.m.

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

Михаиллл
  • Feb. 11, 2019, 9:39 a.m.

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

М
  • March 27, 2019, 7:17 a.m.

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

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

+

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

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

s
  • June 3, 2020, 3 p.m.

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

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

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

}
Михаиллл
  • June 3, 2020, 3:25 p.m.

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

s
  • June 3, 2020, 3:32 p.m.

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

s
  • June 3, 2020, 3:33 p.m.

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

Михаиллл
  • June 3, 2020, 3:50 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 11, 2024, 10:12 p.m.
Django - Tutorial 055. How to write auto populate field functionality Freckles because of several brand names retin a, atralin buy generic priligy
i
innorwallNov. 11, 2024, 6:23 p.m.
QML - Tutorial 035. Using enumerations in QML without C ++ priligy cvs 24 Together with antibiotics such as amphotericin B 10, griseofulvin 11 and streptomycin 12, chloramphenicol 9 is in the World Health Organisation s List of Essential Medici…
i
innorwallNov. 11, 2024, 3:50 p.m.
Qt/C++ - Lesson 052. Customization Qt Audio player in the style of AIMP It decreases stress, supports hormone balance, and regulates and increases blood flow to the reproductive organs buy priligy online safe Promising data were reported in a PDX model re…
i
innorwallNov. 11, 2024, 2:19 p.m.
Heap sorting algorithm The role of raloxifene in preventing breast cancer priligy precio
i
innorwallNov. 11, 2024, 1:55 p.m.
PyQt5 - Lesson 006. Work with QTableWidget buy priligy 60 mg 53 have been reported by Javanovic Santa et al
Now discuss on the forum
i
innorwallNov. 11, 2024, 8:56 p.m.
добавить qlineseries в функции buy priligy senior brother Chu He, whom he had known for many years
i
innorwallNov. 11, 2024, 10:55 a.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks