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>
相关推荐
一只小风华~2 小时前
Vue:条件渲染 (Conditional Rendering)
前端·javascript·vue.js·typescript·前端框架
柯南二号2 小时前
【大前端】前端生成二维码
前端·二维码
程序员码歌2 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
博客zhu虎康3 小时前
React Hooks 报错?一招解决useState问题
前端·javascript·react.js
灰海3 小时前
vue中通过heatmap.js实现热力图(多个热力点)热区展示(带鼠标移入弹窗)
前端·javascript·vue.js·heatmap·heatmapjs
王源骏4 小时前
LayaAir鼠标(手指)控制相机旋转,限制角度
前端
大虾写代码4 小时前
vue3+TS项目配置Eslint+prettier+husky语法校验
前端·vue·eslint
wordbaby4 小时前
用 useEffectEvent 做精准埋点:React analytics pageview 场景的最佳实践与原理剖析
前端·react.js
上单带刀不带妹4 小时前
在 ES6 中如何提取深度嵌套的对象中的指定属性
前端·ecmascript·es6