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
ДЛ

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

  • Result:60points,
  • Rating points-1
СЦ

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

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

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

  • Result:73points,
  • Rating points1
Last comments
J
JonnyJoMarch 30, 2023, 11:57 a.m.
Qt/C++ - Lesson 021. The drawing mouse in Qt Евгений, здравствуйте! Только начал изучение Qt и возник вопрос по 21ому уроку. После написания кода, выдаёт следующие ошибки В чём может быть проблема?
АН
Алексей НиколаевMarch 26, 2023, 9:10 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 9:04 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 24, 2023, 2:35 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 10:09 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
Now discuss on the forum
BlinCT
BlinCTApril 1, 2023, 5:16 a.m.
Нужен совет по работе с ListView и несколькими моделями Спасибо, сейчас займусь этим.
NSProject
NSProjectMarch 31, 2023, 2:55 a.m.
Проверка комментария принадлежит он пользователю или нет DRF (Django Rest Framework) Здравствуйте! Сегодня я столкнулся с такой проблеммой. Существует модель комметариев. Где их соответственно достаточное количество. Все они выводятся при помощи запроса ajax (axios). Так ка…
P
PisychMarch 30, 2023, 2:50 a.m.
Как подсчитать количество по условию? Да! Вот так работает! Огромное Вам спасибо! ........
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 29, 2023, 3:17 p.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.

Follow us in social networks