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>
相关推荐
Winson℡29 分钟前
React Native 中的 useCallback
javascript·react native·react.js
wyzqhhhh31 分钟前
less和sass
前端·less·sass
Nan_Shu_6142 小时前
学习:uniapp全栈微信小程序vue3后台-额外/精彩报错篇
前端·学习·微信小程序·小程序·uni-app·notepad++
excel3 小时前
Vue3 中的双向链表依赖管理详解与示例
前端
谢尔登3 小时前
【Nest】基本概念
javascript·node.js·express
前端小白从0开始3 小时前
Chrome DevTools高级用法:性能面板内存泄漏排查
前端·chrome·chrome devtools
EveryPossible4 小时前
带有渐变光晕
前端·javascript·css
jojo是只猫4 小时前
Vue 3 开发的 HLS 视频流播放组件+异常处理
前端·javascript·vue.js
卓码软件测评4 小时前
第三方软件登记测试机构:【软件登记测试机构HTML5测试技术】
前端·功能测试·测试工具·html·测试用例·html5
CS Beginner4 小时前
【html】canvas实现一个时钟
前端·html