qml加载html以及交互
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.15Window {width: 800height: 600visible: trueQtObject {id: bridgeproperty string currentTime: new Date().toTimeString()WebChannel.id: "qmlBridge" // JS object// signal for js listensignal callJs(string strData);// html -> QMLfunction showMessage(msg) {console.log("Js invoke: ", msg)}// QML -> htmlfunction callJavaScript(message) {console.log("Invoke js func " )callJs(message)currentTime = new Date().toTimeString()// invoke js functionwebview.runJavaScript("getResult(5, 10);", function(result) {console.log("JS returns: ", result)})}}WebChannel {id: webChannelregisteredObjects: [bridge]}WebEngineView {id: webviewanchors.fill: parentwebChannel: webChannelurl: "qrc:/html/index.html"Component.onCompleted: {}}Button {text: "Invoke js"anchors.bottom: parent.bottomonClicked: {bridge.callJavaScript(new Date().toLocaleTimeString());}}
}
3、html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><script src="qrc:/html/qwebchannel.js"></script><script>// global functionfunction getResult(a, b) {return a + b;}// functionfunction handleQMLmsg(message) {alert(message)document.getElementById("time").innerText = message;}window.onload = function() {// init QWebChannelnew QWebChannel(qt.webChannelTransport, function(channel) {const bridge = channel.objects.qmlBridge;// invoke QMLdocument.getElementById("btn").onclick = function() {bridge.showMessage("HTML invoke QML");};// bind qml signalbridge.callJs.connect(handleQMLmsg);// bind qml properitybridge.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>