如何正确地将值从 pyqt 返回到 JavaScript?
我已经在下面的答案中找到并编辑了。
我想将值从 python 代码返回到 QtWebKit 中的 javascript 上下文。到目前为止,我有一个像这样的类:
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)
我可以像这样从 Javascript 调用这个函数:
var a = extensions.constant_one();
它确实被调用了(我用那里的打印进行了验证);但 a 仍然最终未定义。为什么 a 没有得到函数的返回值?我也尝试将 a 包装在 QVariant 中,但到目前为止还没有骰子。
编辑:我找到了答案。显然,QtWebKit 需要结果类型作为提示。我们可以将其提供给 pyqtSlot-Decorator,如下所示:
class Extensions(QtCore.QObject):
@QtCore.pyqtSlot(result="int")
def constant_one(self):
return 1;
然后它就可以正常工作了。将其再保留两天,以防有人发现我应该做的其他事情。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发布问题后不久,我自己找到了答案:显然,QtWebKit 需要结果类型作为提示。我们可以将其提供给 pyqtSlot-Decorator,如下所示:
然后它就可以正常工作了。
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:
and then it works correctly.