肥仔教程网

SEO 优化与 Web 开发技术学习分享平台

在pyside的QWebEngineView中和javascript通信

在pyside2中可以使用QtWebChannel 使QWebEngineView和前端页面的javasccript通信

代码:

from PySide2.QtWebChannel import QWebChannel
from PySide2.QtCore import QUrl, Signal, Slot, QObject
from PySide2.QtWebEngineWidgets import QWebEngineProfile, QWebEnginePage, QWebEngineSettings,QWebEngineView
#创建一个桥
class Bridge(QObject):
    #信号槽函数 接收javascript发送的消息
    @Slot(str)
    def js_message(self, text):
        # 这里可以处理从 JavaScript 接收到的选择内容
        print(text)
    # Python反馈消息给JavaScript  
    @Slot(str, result=str)  
    def python_message(self, text):  
        # 处理消息,并返回结果  
        result = f"Python收到: {text}, 回复: 你好!"  
        return result 

#自定义一个QWebEngineView类
class MyWebEngineView(QWebEngineView):
    def __init__(self, parent=None):
        super(MyWebEngineView, self).__init__(parent)


        page = QWebEnginePage()
        self.setPage(page)
        #创建QWebChannel
        self.channel = QWebChannel()
        self.bridge = Bridge()
        #将bridge注册到QWebChannel
        self.channel.registerObject('bridge', self.bridge)
        self.page().setWebChannel(self.channel)

    #重写setHtml 对加载的页面增加qwebchannel.js的调用和 上面bridge对象的调用
    def setHtml(self, html_content):
        modified_html = html_content+"""
            <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
            <script>
                var bridge;
               new QWebChannel(qt.webChannelTransport, function (channel) {
                   bridge = channel.objects.bridge;
               });
               var message= '发送给python程序'
                bridge.js_message(html);
            </script>   
            """
        super(MyWebEngineView, self).setHtml(modified_html)
上面示例介绍了前端页面加载的时候,发送给pyside信息.

如果是接收python发送来的消息,如下面实现:
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>  
<script>  
    var bridge;  
    new QWebChannel(qt.webChannelTransport, function (channel) {  
        bridge = channel.objects.bridge;  
  
        // 调用Python方法  
        bridge.python_message('Hello from JavaScript').then(function(result) {  
            console.log(result);  // 输出Python的回复  
        });  
        
    });  
</script>
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言