文章目录
- 参考
- 示例1
- TestWebenqine.pro
- mainwindow.h
- mainwindow.cpp
- main.cpp
- 效果
- 示例2 (使用setDevToolsPage函数)
- main.cpp
- 效果
参考
QT webengine显示HTML简单示例
示例1
- 编译器 : Desktop Qt 5.15.2 MSVC2019 64bit
- 编辑器: QtCreator
- 代码:
TestWebenqine.pro
# TestWebenqine.pro
QT += core gui webenginewidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#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
//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();
//使得网页的窗口大小随着mainwindow的窗口大小变化而变化
void resizeEvent(QResizeEvent *event);
private:
Ui::MainWindow *ui;
QWebEngineView *view; //声明view
};
#endif // MAINWINDOW_H
mainwindow.cpp
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QResizeEvent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
view = new QWebEngineView(this);
//view->setFixedSize(this->width(),this->height());
view->load(QUrl(QStringLiteral("https://www.qweather.com/weather/luoyang-101180901.html")));
//view->load(QUrl(QStringLiteral("https://www.baidu.com")));
view->showMaximized();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event); // 调用基类的 resizeEvent,确保正常的处理
// 获取新的 mainwindow 大小
QSize newSize = event->size();
// 将新的大小应用于 view
view->setFixedSize(newSize.width(), newSize.height());
}
main.cpp
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
效果
示例2 (使用setDevToolsPage函数)
- 编译器 : Desktop Qt 5.15.2 MSVC2019 64bit
- 编辑器: QtCreator
- 代码:
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QWebEngineView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//MainWindow w;
//w.show();
QWebEngineView *view = new QWebEngineView();
QWebEngineView *view1 = new QWebEngineView();
view->setUrl(QUrl("http://baidu.com"));
view->page()->setDevToolsPage(view1->page());
view->setWindowTitle("BaiDu");
view1->setWindowTitle("DevTool");
view->show();//显示页面
view1->show();//显示view页面的JS脚本(也就是说:view1是view的开发者工具)
return a.exec();
}