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>
相关推荐
学嵌入式的小杨同学5 小时前
从零打造 Linux 终端 MP3 播放器!用 C 语言实现音乐自由
linux·c语言·开发语言·前端·vscode·ci/cd·vim
weixin_425543736 小时前
TRAE CN3.3.25 构建的Electron简易DEMO应用
前端·typescript·electron·vite·nestjs
Mr Xu_7 小时前
【Vue3 + ECharts 实战】正确使用 showLoading、resize 与 dispose 避免内存泄漏
前端·信息可视化·vue·echarts
0思必得07 小时前
[Web自动化] Selenium设置相关执行文件路径
前端·爬虫·python·selenium·自动化
雯0609~7 小时前
hiprint:实现项目部署与打印1-官网提供普通html版本
前端·html
yuezhilangniao7 小时前
AI智能体全栈开发工程化规范 备忘 ~ fastAPI+Next.js
javascript·人工智能·fastapi
不绝1917 小时前
UGUI——进阶篇
前端
Exquisite.8 小时前
企业高性能web服务器(4)
运维·服务器·前端·网络·mysql
铅笔侠_小龙虾8 小时前
Flutter Demo
开发语言·javascript·flutter
2501_944525548 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter