how do I correctly return values from pyqt to Java

2020-08-23 01:16发布

问题:

I already found and edited in an answer below.

I want to return values from python code to javascript context within QtWebKit. So far, I have a class like this:

class Extensions(QtCore.QObject):
  @QtCore.pyqtSlot()
  def constant_one(self):
    return 1;
# ... later, in code
e = Extensions();
def addextensions():
  webview.page().mainFrame().addToJavaScriptWindowObject("extensions", e);
# ... 
webview.connect(webview.page().mainFrame(), QtCore.SIGNAL("javaScriptWindowObjectCleared"), addextensions)

I can call this function from Javascript like so:

var a = extensions.constant_one();

and it does get called indeed (I verified with a print in there); but a still ends up undefined. Why doesn't a get the value returned from the function? I also tried wrapping a in a QVariant, but no dice so far.

Edit: I found the answer. Apparently, QtWebKit needs the result type as a hint. One can provide that to the pyqtSlot-Decorator, like this:

class Extensions(QtCore.QObject):
  @QtCore.pyqtSlot(result="int")
  def constant_one(self):
    return 1;

and then it works correctly. Leaving this open for another two days, in case someone finds something else I should be doing.

回答1:

shortly after posting the question, I found the answer myself: Apparently, QtWebKit needs the result type as a hint. One can provide that to the pyqtSlot-Decorator, like this:

class Extensions(QtCore.QObject):
  @QtCore.pyqtSlot(result="int") # just int (type object) also works
  def constant_one(self):
    return 1;

and then it works correctly.



标签: qt pyqt qtwebkit