2017-04-20 107 views
1

我想调用从QML的HTML中重新加载函数。我可以在HTML中调用QML函数,如下面的代码所示。如何从QML调用HTML函数

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的装载功能。

回答

1

你可以叫runJavaScript功能如下

function callHtmlFunction(){ 
    view.runJavaScript("reload("+ color +")"); 
}