如何正确地将值从 pyqt 返回到 JavaScript? [英] how do I correctly return values from pyqt to JavaScript?

查看:45
本文介绍了如何正确地将值从 pyqt 返回到 JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到并编辑了下面的答案.

我想将值从 python 代码返回到 QtWebKit 中的 javascript 上下文.到目前为止,我有一个这样的类:

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)

我可以像这样从 Javascript 调用这个函数:

I can call this function from Javascript like so:

var a = extensions.constant_one();

它确实被调用了(我在那里打印了验证);但 a 仍然最终未定义.为什么不获取函数返回的值?我还尝试将 a 包装在 QVariant 中,但到目前为止还没有骰子.

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.

我找到了答案. 显然,QtWebKit 需要结果类型作为提示.可以将其提供给 pyqtSlot-Decorator,如下所示:

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.

推荐答案

发布问题后不久,我自己找到了答案:显然,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:

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.

这篇关于如何正确地将值从 pyqt 返回到 JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆