Pyside6加载本地html文件并实现与Javascript进行通信

代码参考:pyqt、pyside与QWebEngine前端js交互简单示例_pyside js-CSDN博客

进行修复:修复js引入,修复html文件加载,更新库和修复一些报错

main.py

python 复制代码
import sys
import time
import os

from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QObject, Slot
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtCore import QTimer


class Handlers(QObject):

    def __init__(self):
        super().__init__(None)
        self.view = QWebEngineView()
        self.page = self.view.page()
        # 定时发送测试消息的定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.send_time)
        # 页面加载完成后再启动定时器
        self.view.loadFinished.connect(self.on_load_finished)

    @Slot(str, result=str)
    def hello(self, message):
        """js调用python测试"""
        print('call received')
        return f'hello from python: {
     
     message}'

    def on_load_finished(self, success):
        """页面加载完成回调"""
        if success:
            print("页面加载完成,启动定时器")
            self.timer.start(1000)  # 修改为1秒一次,避免调用过于频繁
    
    def send_time(self):
        """python调用js测试"""
        # 先检查sysTime函数是否存在
        self.page.runJavaScript("typeof sysTime !== 'undefined'", lambda exists: {
            'result': exists and self.page.runJavaScript(f"sysTime('python 本地时间: {time.time()}')")
        })


if __name__ == '__main__':
    app = QApplication(sys.argv)

    channel = QWebChannel()
    handlers = Handlers()
    channel.registerObject('py', handlers)
    handlers.page.setWebChannel(channel)
    from PySide6.QtCore import QUrl
    html_file_path = os.path.abspath(os.path.join(os.getcwd(), 'testpytohtml', 'index.html'))
    print(f"加载HTML文件路径: {html_file_path}")
    handlers.view.load(QUrl.fromLocalFile(html_file_path))
    handlers.view.show()
    # 确保在QApplication事件循环开始前有足够时间初始化
    import time
    time.sleep(0.5)
    sys.exit(app.exec())

index.html

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <!-- 使用PySide6内置的qwebchannel.js 用QT通信协议qrc架加载-->
    <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <title>QWebChannel测试</title>
    <script>
    	//初始化代码,固定格式
        window.onload = function () {
     
     
            new QWebChannel(qt.webChannelTransport, function (channel) {
     
     
                window.py = channel.objects.py;
            });
        }
    </script>
</head>
<body>
<div id="sysTime" style="padding:5px;border: 2px solid green"></div>
<div style="margin-top: 10px;padding:5px;border: 2px solid green">
    <input id="message" name="message"/>
    <button onclick="sendMessage();">发送消息</button>
</div>
<script>
    function sendMessage() {
     
     
        message = document.getElementById('message').value;
        //调用python的hello方法
        py.hello(message, function(res){
     
     
            alert(res);
        });
    }
	//给python调用的显示时间的测试方法
    function sysTime(msg) {
     
     
        document.getElementById('sysTime').innerHTML=msg;
    }


</script>
</body>
</html>
相关推荐
泷羽Sec-静安11 分钟前
Less-1 GET-Error based-Single quotes-String GET-基于错误-单引号-字符串
前端·css·网络·sql·安全·web安全·less
小时前端22 分钟前
虚拟DOM已死?90%内存节省的Vapor模式正在颠覆前端
前端·html
Keepreal49624 分钟前
Web Components简介及如何使用
前端·javascript·html
进击的野人27 分钟前
JavaScript变量声明的前世今生:从var到let/const的演进
javascript
jump68030 分钟前
TS中 unknown 和 any 的区别
前端
无羡仙39 分钟前
AI终于‘看见’网页了!Stagewise让UI修改从‘盲调’变‘指哪打哪
前端
柯腾啊1 小时前
“Script error.”的产生原因和解决办法
前端·javascript·浏览器
沙漠之皇1 小时前
ts 定义重复对象字段
前端
HashTang2 小时前
不用再配服务器了!这套 Next.js + Cloudflare 模板,一个人搞定全栈出海
前端·后端·边缘计算
Cory.眼2 小时前
WebRTC入门指南:实时通信零基础
javascript·webrtc·实时通信