试了一天,终于调通了。贴代码~
Python主函数代码
import sys import Web_UI from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject,pyqtProperty from PyQt5.QtWebChannel import QWebChannel from MySharedObject import MySharedObject from PyQt5.QtWidgets import QApplication import os BASE_DIR = os.path.dirname(__file__)#获取当前文件夹的绝对路径 if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QFrame() ui = Web_UI.Ui_Form() ui.setupUi(MainWindow) ui.webView1.load(QtCore.QUrl(r""+BASE_DIR+"/web_file3.html")) channel = QWebChannel() ##创建一个QwebChannel对象,用于传递PyQt的参数到JavaScript myObj = MySharedObject() print(myObj.strval) channel.registerObject('bridge', myObj) ui.webView1.page().setWebChannel(channel) MainWindow.show() sys.exit(app.exec_())
继承了QWidget类的MySharedObject(Python文件)
from PyQt5.QtCore import QObject from PyQt5.QtCore import pyqtProperty from PyQt5.QtWidgets import QWidget,QMessageBox class MySharedObject(QWidget): def __init__(self,strval = '100'): super(MySharedObject,self).__init__() self.strval = strval def _getStrValue(self): return self.strval def _setStrValue(self,str): self.strval = str print('获得页面参数:%s'% str) QMessageBox.information(self,"Infomation", '获得的页面参数%s' % str) #需要定义的对外发布的方法 strValue= pyqtProperty(str,_getStrValue,_setStrValue)
页面代码HTML
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>A Demo Page</title> <script src = "qwebchannel.js"></script> <script language = "javascript"> function completeAndReturnName(){ var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var fullname = fname +' '+ lname; document.getElementById('fullname').value = fullname; document.getElementById('submit-btn').style.display = 'block'; return fullname; } document.addEventListener("DOMContentLoaded",function(){ new QWebChannel(qt.webChannelTransport, function (channel) { //alert('111 chanel='+channel) window.bridge = channel.objects.bridge; alert('bridge='+bridge.strValue +'\n从pyqt传来的参数='+window.bridge.strValue); //alert('111 chanel='+ channel.objects.strValue) }) } ) function onShowMsgBox() { if(window.bridge != null){ var fname = document.getElementById('fname').value; window.bridge.strValue = fname; //调用对象 } } </script> </head> <body> <form> <label id = "name">User Name:</label> <input type = "text" name = "fname" id = "fname"></input> <br /> <input type = "button" value="传递参数到pyqt" onclick="onShowMsgBox()"></input> <br /> <input type = "reset" value="重置"></input> </form> </body> </html>
实现效果