来自python的返回值在javascript中不可用

时间:2017-04-11 12:40:14

标签: javascript python pyqt5

我正在开发一个pyqt5应用程序,它打开了一个Qwebengineview。我还将一个处理程序附加到QWebchannel,以便在javascript和python方法之间进行通信,并将其设置为QWebengineview。

一切都按预期工作。上面的代码加载HTML,并且从javascript调用CallHandler的test()方法。它运行顺利。 但是,当从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中不可用。

2 个答案:

答案 0 :(得分:1)

函数调用getScriptsPath的结果是异步返回的,因此您必须将回调函数传递给处理程序以检索结果,例如:

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

答案 1 :(得分:1)

a,b,c是您从js传递给py的参数

file_path是从py到js异步

handler.getScriptsPath(a,b,c,function(file_path) {
    console.log(file_path);
});