qml加载html,采用webchannel进行通信,需绑定对象
1、main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWebChannel>
#include <QQmlContext>
int main(int argc, char *argv[]) {
QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
2、main.qml
import QtQuick 2.15
import QtWebEngine 1.10
import QtWebChannel 1.0
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
width: 800
height: 600
visible: true
QtObject {
id: bridge
property string currentTime: new Date().toTimeString()
WebChannel.id: "qmlBridge" // JS object
// signal for js listen
signal callJs(string strData);
// html -> QML
function showMessage(msg) {
console.log("Js invoke: ", msg)
}
// QML -> html
function callJavaScript(message) {
console.log("Invoke js func " )
callJs(message)
currentTime = new Date().toTimeString()
// invoke js function
webview.runJavaScript("getResult(5, 10);", function(result) {
console.log("JS returns: ", result)
})
}
}
WebChannel {
id: webChannel
registeredObjects: [bridge]
}
WebEngineView {
id: webview
anchors.fill: parent
webChannel: webChannel
url: "qrc:/html/index.html"
Component.onCompleted: {
}
}
Button {
text: "Invoke js"
anchors.bottom: parent.bottom
onClicked: {
bridge.callJavaScript(new Date().toLocaleTimeString());
}
}
}
3、html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="qrc:/html/qwebchannel.js"></script>
<script>
// global function
function getResult(a, b) {
return a + b;
}
// function
function handleQMLmsg(message) {
alert(message)
document.getElementById("time").innerText = message;
}
window.onload = function() {
// init QWebChannel
new QWebChannel(qt.webChannelTransport, function(channel) {
const bridge = channel.objects.qmlBridge;
// invoke QML
document.getElementById("btn").onclick = function() {
bridge.showMessage("HTML invoke QML");
};
// bind qml signal
bridge.callJs.connect(handleQMLmsg);
// bind qml properity
bridge.currentTimeChanged.connect(function() {
//alert(bridge.currentTime)
//document.getElementById("time").innerText = bridge.currentTime;
});
});
};
</script>
</head>
<body>
<h2>Qml interactive with html</h2>
<p>QML invoke js: <span id="time"></span></p>
<button id="btn">Invoke QML</button>
</body>
</html>