QT 调用QWebEngineView显示网页

Posted ʚVVcatɞ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QT 调用QWebEngineView显示网页相关的知识,希望对你有一定的参考价值。

环境:

  • Windows:10
  • C++ Qt:5.14.1

步骤:
第一步:需要在 xxxxx.pro 下添加 QT += webenginewidgets
第二步:mainwindow.h中添加 QWebEngineView 属性
第三步:mainwindow.cpp 中创建 QWebEngineView 对象,并使用QWebEngineView 里的方法。

Use_QWebEngineView.pro

# 添加 webenginewidgets
QT       += core gui webenginewidgets

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = web
TEMPLATE = app

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \\
    main.cpp \\
    mainwindow.cpp

HEADERS += \\
    mainwindow.h

FORMS += \\
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWebEngineView>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    QWebEngineView *view;
    void setWebview();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

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

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

    view = new QWebEngineView(this);
    view->resize(1920, 1080); // 设置窗口大小
    setWebview();
}

void MainWindow::setWebview(){
    view->page()->load(QUrl("http://www.baidu.com"));  //打开百度
    view->show(); // 显示视图

}

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

运行结果:

以上是关于QT 调用QWebEngineView显示网页的主要内容,如果未能解决你的问题,请参考以下文章

QT调用IE浏览器COM插件完成网页浏览

Qt嵌入网页

Qt嵌入网页

Qt编程使用QWebEngineView加载网页后,左键点击链接没反应,不能打开链接要怎么解决

qwebengineview如何让js调用qt中的方法

Linux + Qt : QWebEngineView + QWebChannel 与 JS 交互传递信息