如何从 QML 调用 HTML 函数
How to call HTML function from QML
我想从 QML 调用 HTML 中的 reload 函数。我可以从 HTML 调用 QML 函数,如下面的代码所示。
QML 文件:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.0
import QtWebChannel 1.0
Window {
visible: true
width: 640
height: 480
QtObject {
id: myQmlObj
WebChannel.id: "myQmlObj";
signal someSignal(string msg);
function someFoo(msg) {
console.log(msg);
}
}
WebEngineView {
id: view
anchors.fill: parent
url: "myHtml.html"
WebChannel {
id: webChannel
registeredObjects: [myQmlObj]
}
}
}
HTML 文件:
<html>
<body>
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
var color = 1;
var webChannel;
function init() {
color = 5;
};
function createChannel(lat) {
new QWebChannel(qt.webChannelTransport, function (channel) {
webChannel = channel.objects.myQmlObj;
webChannel.someSignal.connect("someSignal");
webChannel.someFoo("someFoo");
});
}
function reload(id) {
color = id;
}
</script>
<script src="someUrl?callback=init"></script>
</body>
</html>
就像我可以从 HTML 调用 someFoo(),但是我不能从我的 qml 调用 HTML 的重载函数。
您可以调用 runJavaScript 函数如下
function callHtmlFunction(){
view.runJavaScript("reload("+ color +")");
}
我想从 QML 调用 HTML 中的 reload 函数。我可以从 HTML 调用 QML 函数,如下面的代码所示。
QML 文件:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.0
import QtWebChannel 1.0
Window {
visible: true
width: 640
height: 480
QtObject {
id: myQmlObj
WebChannel.id: "myQmlObj";
signal someSignal(string msg);
function someFoo(msg) {
console.log(msg);
}
}
WebEngineView {
id: view
anchors.fill: parent
url: "myHtml.html"
WebChannel {
id: webChannel
registeredObjects: [myQmlObj]
}
}
}
HTML 文件:
<html>
<body>
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
var color = 1;
var webChannel;
function init() {
color = 5;
};
function createChannel(lat) {
new QWebChannel(qt.webChannelTransport, function (channel) {
webChannel = channel.objects.myQmlObj;
webChannel.someSignal.connect("someSignal");
webChannel.someFoo("someFoo");
});
}
function reload(id) {
color = id;
}
</script>
<script src="someUrl?callback=init"></script>
</body>
</html>
就像我可以从 HTML 调用 someFoo(),但是我不能从我的 qml 调用 HTML 的重载函数。
您可以调用 runJavaScript 函数如下
function callHtmlFunction(){
view.runJavaScript("reload("+ color +")");
}