1.通过QWebEngineView引入html页面, .pro文件中引入webenginewidgets,webengine,network,webchannel组件
组件可以通过QT软件根目录的MaintenanceTool.exe安装,设置中选择临时资料档案库,临时资料档案库可以在网上找资源路径(我用的是:http://mirrors.ustc.edu.cn/qtproject/online/qtsdkrepository/mac_x64/root/qt/,如果临时资料档案库测试是失败的,可能是因为没有装visual studio),选择添加或移除组件
2.建立连接html和QT的QObject类
mychannel.h
#ifndef MYCHANNEL_H
#define MYCHANNEL_H
#include <QObject>
#include <QDebug>
#include <QWebChannel>
class MyChannel : public QObject
{
Q_OBJECT
public:
explicit MyChannel(QObject *parent = nullptr);
void sendSetViewPort();
signals:
void setViewPort();//QT给html页面发送的信号
};
#endif // MYCHANNEL_H
mychannel.cpp
#include "mychannel.h"
MyChannel::MyChannel(QObject *parent) : QObject(parent)
{
}
void MyChannel::sendSetViewPort()
{
qDebug()<<"----------------alert==========";
emit setViewPort();
}
mapload.cpp(加载html页面的cpp文件)
void MapLoad::initMap(){
_myChannel = new MyChannel(this);
QWebChannel* web_channel = new QWebChannel(this);
//html文件用的时候可以知道用的是哪个webchannel
web_channel->registerObject("qtChannel",_myChannel);
//加载html页面的widget
view = new QWebEngineView(ui->widget_map_content);
view->load(QUrl("qrc:/font/images/static/mapindex.html"));
view->page()->setWebChannel(web_channel);
view->show();
//点击按钮的时候给发给MapLoad发送点击事件的信号
QObject::connect(ui->button_right, &QPushButton::clicked, this, &MapLoad::sendSetViewPort);
}
void MapLoad::sendSetViewPort()
{
qDebug()<<"----------------alert";
_myChannel->sendSetViewPort();
}
mapload.h
private:
Ui::MapLoad *ui;
QWebEngineView *view=nullptr;
MyChannel* _myChannel=nullptr;
private slots:
void on_button_right_clicked();
void sendSetViewPort();
mapindex.html
<script type="text/javascript" src="./qwebchannel.js"></script>
<script type="text/javascript">
var mchannel;
window.onload = function () {
if (typeof qt != 'undefined') {
new QWebChannel(qt.webChannelTransport, function (channel) {
channel.objects.qtChannel.setViewPort.connect(mapSetView);
})
} else {
alert("qt对象获取失败!");
}
}
function mapSetView() {
console.log("nihao");
}
</script>
参考:https://blog.csdn.net/qq_41961619/article/details/107104622