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>
相关推荐
一只小阿乐18 小时前
react 封装弹框组件 传递数据
前端·javascript·react.js
533_18 小时前
[element-plus] el-tree 动态增加节点,删除节点
前端·javascript·vue.js
禁止摆烂_才浅18 小时前
前端开发小技巧-【JavaScript】- 获取元素距离 document 顶部的距离
前端·javascript·react.js
wshzd18 小时前
LLM之Agent(二十九)|LangChain 1.0核心组件介绍
前端·javascript·langchain
程序猿_极客18 小时前
Vue 2脚手架从入门到实战核心知识点全解析(day6):从工程结构到高级通信(附代码讲解)
前端·javascript·vue.js·vue2学习笔记
q***718518 小时前
海康威视摄像头ISUP(原EHOME协议) 摄像头实时预览springboot 版本java实现,并可以在浏览器vue前端播放(附带源码)
java·前端·spring boot
一只小阿乐18 小时前
vue3 使用v-model开发弹窗组件
javascript·vue.js·elementui
web加加19 小时前
vue3 +vite项目页面防f12,防打开控制台
前端·javascript·vue.js
A尘埃19 小时前
大模型应用python+Java后端+Vue前端的整合
java·前端·python
遥遥晚风点点20 小时前
Spark导出数据文件到HDFS
前端·javascript·ajax