pro文件
文件中需要加入”QT += core gui webenginewidgets”这句话,不然提示找不到文件
QT += core gui
QT += core gui webenginewidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = WebEngine
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as 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 you use 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 \
cwebconnct.cpp
HEADERS += \
mainwindow.h \
cwebconnct.h
FORMS += \
mainwindow.ui
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QWebEngineView>
#include <QWebChannel>
#include "cwebconnct.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWebEngineView view;
//view.setUrl(QUrl(QStringLiteral("http://html5test.com")));
view.setUrl(QUrl("file:///C:/Users/Documents/QT/WebEngine/html/test.html"));
view.resize(1024, 768);
view.show();
QWebChannel* webchannel= new QWebChannel(&view);
CWebConnct webconnet(NULL);
webchannel->registerObject(QStringLiteral("content"),&webconnet);
view.page()->setWebChannel(webchannel);
return a.exec();
}
桥接类
#ifndef CWEBCONNCT_H
#define CWEBCONNCT_H
#include <QObject>
#include <QDebug>
class CWebConnct : public QObject
{
Q_OBJECT
public:
explicit CWebConnct(QObject *parent = nullptr);
signals:
void sendText(const QString &text);
public slots:
void receiveText(const QString &r_text);
};
#endif // CWEBCONNCT_H
#include "cwebconnct.h"
CWebConnct::CWebConnct(QObject *parent) : QObject(parent)
{
}
void CWebConnct::receiveText(const QString &r_text)
{
qDebug()<<(QObject::tr("Received message: %1").arg(r_text));
emit sendText(r_text);//此处是异步通信 qDebug()<<(QObject::tr("Received message end"));
}
测试的html文件
需要在html中引用qwebchannel.js文件
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>弹窗</title>
<script type="text/javascript" src="./qwebchannel.js"></script>
<script type="text/javascript">
window.onload = function() { //所有的必须在里面进行写吗???
var content;
new QWebChannel(qt.webChannelTransport, function(channel) {
// make dialog object accessible globally
content = channel.objects.content; //把对象赋值到JS中
document.getElementById("sendtest").onclick=function (){
content.receiveText("sss");
}
content.sendText.connect(function(message) { //连接QT中发出的信号,里面的message是参数;只需要在QT中调用此函数也就是sendText就可以调用JS函数
alert("Received message: " + message);
});
});
}
</script>
</head>
<body>
<button id="sendtest" >测试webchannel</button>
</html>