如何在 QWebEngineView 中从 QML 传递值到 JavaScript?

5

DataManager是一个类,在QML中可以通过以下代码(Qt版本5.8.0)进行访问。

DataManager *d = new DataManager;
QQuickView *viewver = new QQuickView;
viewver->rootContext()->setContextProperty("dataManager", d);

现在在QML中,我创建了一个WebEngineView并加载了一个本地的HTML文件,运行良好。

WebEngineView{
    id : webEnginView
    anchors.fill: parent
    url : dataManager.htmlURL();
}

现在,我想在已加载的HTML文件的JavaScript代码中访问dataManager的值。提前致谢。
1个回答

10

QML 代码

import QtQuick 2.0
import QtWebEngine 1.4
import QtWebChannel  1.0

Item{
    id:root
    height: 500
    width:  500

// Create WebChannel
WebChannel{
    id:webChannel
}

//Now, let’s create an object that we want to publish to the HTML/JavaScript clients:
QtObject {
    id: myObject
    objectName: "myObject"

    // the identifier under which this object
    // will be known on the JavaScript side
    //WebChannel.id: "webChannel"

    property var send: function (arg) {
                sendTextMessage(arg);
            }

    // signals, methods and properties are
    // accessible to JavaScript code
    signal someSignal(string message);


    function someMethod(message) {
        console.log(message);
        someSignal(message);
        return dataManager.getGeoLat();
    }

    property string hello: "world";
}

Rectangle{
    anchors.fill: parent
    color: "black"

WebEngineView{
    id : webEnginView
    anchors.fill: parent
    url : dataManager.htmlURL();
    webChannel: webChannel
}
}

Component.onCompleted: {
    webChannel.registerObject("foo", myObject);
    //Expose C++ object 
    webChannel.registerObject("bar", dataManager);
}
}

HTML 代码

<script type="text/javascript" src="qrc:/Map/qwebchannel.js"></script>
<script type="text/javascript">
new QWebChannel(qt.webChannelTransport, function(channel) {
    // all published objects are available in channel.objects under
    // the identifier set in their attached WebChannel.id property
    var foo = channel.objects.foo;
    var dManager = channel.objects.bar;

    // access a property
    alert(foo.hello);

    // connect to a signal
    foo.someSignal.connect(function(message) {
        alert("Got signal: " + message);
    });

    // invoke a method, and receive the return value asynchronously
       foo.someMethod("bar", function(ret) {
       alert("Got return value: " + ret);
    });
});
</script>

你是一位超级巨星!!!你的解决方案非常完美!!感谢你与我们所有人分享这个! - zeFree

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接