<html>
<head>
<meta charset="UTF-8" />
<title>QWebChannel在vue版本的使用</title>
<script src="./qwebchannel.js"></script>
<!-- 引入Vue 注意地址-->
<script type="text/javascript" src="./vue.min.js"></script>
</head>
<body>
<h1>Python-JavaScript 交互测试</h1>
<button onclick="send_message_to_python()">Call Python Function</button>
<div id='app'>
<input type='button' onclick='getInfo()' value="获取机器信息">
<h3 >主机名: </h3>
<h3 >IP: </h3>
<h3 >操作系统: </h3>
<h3 >CPU: </h3>
<label id='info'></label>
</div>
</body>
<!-- 引入demo html中的QWebChannel.js -->
<script>
new Vue({
el: '#app',
mounted() {
// qt通讯
if (typeof qt != 'undefined') {
window.channel = new QWebChannel(qt.webChannelTransport, (channel) => {
window.py_object = channel.objects.python_object;
alert("mounted")
})
}else{
alert("qc对象未获取到!");
}
},
methods: {
// 前端主动调python数据
getInfo() {
window.py_object.putdata()
},
// python中通过putdata函数,回调onGetInfo渲染页面,此页面内容可由前端开发
onGetInfo(info) {
alter('info1',info)
this.defaulitValue = JSON.stringify(info)
var h3Tags = document.getElementsByTagName('h3');
for (var i = 0; i < h3Tags.length; i++) {
h3Tags[i].innerHTML += Object.values(JSON.parse(this.defaulitValue))[i];
}
},
// 前端传参到python
send_message_to_python() {
alert(window.py_object)
var channel = new QWebChannel(qt.webChannelTransport, function (channel) {
// Get Python object
// Call Python object's method
window.py_object.receive_message("Hello from JavaScript!");
});
},
}
})
</script>
</html>
Python 端代码
from PyQt5.QtCore import QUrl, QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
import sys
import os
import json
import socket
import platform
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = "--no-sandbox"
class PythonToJS(QObject):
def __init__(self):
super().__init__()
@pyqtSlot(str, result=str)
def receive_message(self, message):
string = "Received message from JavaScript: " + message
print(string)
return 'true'
@pyqtSlot()
def putdata(self):
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
list_info = platform.uname()
sys_name = list_info[0] + ' ' + list_info[2]
cpu_name = list_info[5]
dic_info = {"hostname": hostname, "ip": ip, "sys_name": sys_name, "cpu_name": cpu_name}
print('Sending info:', dic_info)
view.page().runJavaScript('%s(%s)' % ('onGetInfo', json.dumps(dic_info)))
if __name__ == "__main__":
app = QApplication(sys.argv + ["--no-sandbox"])
view = QWebEngineView()
channel = QWebChannel()
python_object = PythonToJS()
channel.registerObject("python_object", python_object)
view.page().setWebChannel(channel)
curdir = os.getcwd()
url = os.path.join(curdir, 'qtweb.html')
view.load(QUrl.fromLocalFile(url))
view.show()
sys.exit(app.exec_())
我使用vue框架,通过QWebChannel实现页面与python端的数据交互,运行后,python端没有反应。不知问题出现在哪里,如果不用vue,纯js的话,python端是有反应的。