如何正确地将值从 pyqt 返回到 JavaScript?

发布于 2024-11-15 12:25:46 字数 945 浏览 3 评论 0原文

我已经在下面的答案中找到并编辑了。

我想将值从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑾兮 2024-11-22 12:25:46

发布问题后不久,我自己找到了答案:显然,QtWebKit 需要结果类型作为提示。我们可以将其提供给 pyqtSlot-Decorator,如下所示:

class Extensions(QtCore.QObject):
  @QtCore.pyqtSlot(result="int") # just int (type object) also works
  def constant_one(self):
    return 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文