how do I correctly return values from pyqt to JavaScript?

谁都会走 提交于 2019-12-06 23:33:53

问题


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.



来源:https://stackoverflow.com/questions/6372336/how-do-i-correctly-return-values-from-pyqt-to-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!