簡體   English   中英

如何在QWebEngineView中將值從QML傳遞給JavaScript

[英]How to pass value from QML to JavaScript in QWebEngineView

DataManager是一個類,我可以通過下面的代碼(Qt版本5.8.0)在QML中訪問它。

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值。 提前致謝。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM