2017-04-11 27 views
0

我正在开发一个Qwebengineview的pyqt5应用程序。我还将一个处理程序附加到QWebchannel以在JavaScript和Python方法之间进行通信并将其设置为QWebengineview。从python返回的值不可在javascript

一切都按预期工作。上面的代码加载HTML,CallHandler的test()方法从javascript调用。它运行顺利。 但是,当从javascript调用getScriptsPath()方法时,该函数接收该调用,但不返回任何内容。

下面分别是python和HTML代码。

import os 
import sys 
from PyQt5 import QtCore, QtGui 
from PyQt5.QtCore import QUrl, QObject, pyqtSlot 
from PyQt5.QtWidgets import QApplication, QWidget 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWebEngineWidgets import QWebEngineView 
from PyQt5.QtWebChannel import QWebChannel 

class CallHandler(QObject): 
    trigger = pyqtSignal(str) 
    @pyqtSlot() 
    def test(self): 
     print('call received') 

    @QtCore.pyqtSlot(int, result=str) 
    def getScriptsPath(self, someNumberToTest): 
     file_path = os.path.dirname(os.path.abspath(__file__)) 
     print('call received for path', file_path) 
     return file_path 

class Window(QWidget): 
    """docstring for Window""" 
    def __init__(self): 
     super(Window, self).__init__() 
     ##channel setting 
     self.channel = QWebChannel() 
     self.handler = CallHandler(self) 
     self.channel.registerObject('handler', self.handler) 


     self.view = QWebEngineView(self) 
     self.view.page().setWebChannel(self.channel) 

     file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test.html")) 
     local_url = QUrl.fromLocalFile(file_path) 
     self.view.load(local_url) 

def main(): 
    app = QApplication(sys.argv) 
    window = Window() 
    # window.showFullScreen() 
    window.show() 
    sys.exit(app.exec_()) 

if __name__ == "__main__": 
    main() 

HTMLFILE

<html> 
<head> 

</head> 

<body> 
    <center> 
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script> 
    <script language="JavaScript"> 
    var xyz = "HI"; 

    window.onload = function(){ 
      new QWebChannel(qt.webChannelTransport, function (channel) { 
      window.handler = channel.objects.handler; 
      //testing handler object by calling python method. 
      handler.test(); 


      handler.trigger.connect(function(msg){ 
      console.log(msg); 
      }); 
     }); 
    } 

    var getScriptsPath = function(){ 
     file_path = handler.getScriptsPath(); 
     //Logging the recieved value which is coming out as "undefined" 
     console.log(file_path); 
    }; 

    </script> 
    <button onClick="getScriptsPath()">print path</button> 
    </br> 
    <div id="test"> 
     <p>HI</p> 
    </div> 
    </center> 
</body></html> 

我无法破译为什么handler.getScriptsPath()的返回值不是在JavaScript中使用。

回答

0

从你的函数调用getScriptsPath结果asyncronously返回,让你有一个回调函数传递到您的处理检索结果,例如:

handler.getScriptsPath(function(file_path) { 
    console.log(file_path); 
});