如何在 PyQT 5.7 中从 JavaScript 访问 Python 代码? [英] How can I access Python code from JavaScript in PyQT 5.7?

查看:32
本文介绍了如何在 PyQT 5.7 中从 JavaScript 访问 Python 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经通过附加一个对象来做到这一点

I used to do it by attaching an object

self.page().mainFrame().addToJavaScriptWindowObject("js_interface", self.jsi)

在 5.7 中,我这样做:

In 5.7 I do:

self.page().setWebChannel(self.jsi)

但是当我尝试访问公开的函数时,我可以理解地得到一个 JavaScript 错误:

But I understandibly get a JavaScript error when I try to access exposed functions:

js: Uncaught ReferenceError: js_interface is not defined

谷歌搜索我发现我应该使用 qwebchannel.js,但我在任何地方都找不到该文件或有关如何使用它的说明(有一些信息,但仅在安装 QT 时提供的一些示例中,而不是 PyQT).

Googling around I found that I should use qwebchannel.js, but I couldn't find the file or instructions on how to use it anywhere (there was some info, but only in some examples provided when installing QT, not PyQT).

推荐答案

您可以使用 script 标签将 qwebchannel.js 包含到 html 页面中:

You can include qwebchannel.js into html page using the script tag:

<script src="qrc:///qtwebchannel/qwebchannel.js"></script>

然后,在python端创建一个web频道:

Then, create a web channel on the python side:

from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView

class CallHandler(QObject):
    @pyqtSlot()
    def test(self):
        print('call received')

view = QWebEngineView()
channel = QWebChannel()
handler = CallHandler()
channel.registerObject('handler', handler)
view.page().setWebChannel(channel)

与网络频道交互的JS代码:

JS code that interacts with the web channel:

new QWebChannel(qt.webChannelTransport, function (channel) {
    window.handler = channel.objects.handler;
    window.handler.test();
});

这篇关于如何在 PyQT 5.7 中从 JavaScript 访问 Python 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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