我只是在寻找一种可以点击提交按钮的解决方案.这是我从上面的链接中使用的代码,但我没有从表单返回任何值:导入操作系统导入系统从 PyQt5.QtWidgets 导入 QApplication、QVBoxLayout、QWidget从 PyQt5.QtCore 导入 QUrl, QEventLoop从 PyQt5.QtWebEngineWidgets 导入 QWebEngineView从 PyQt5.QtWebEngineCore 导入 QWebEngineUrlRequestInterceptor类网页(QWebEngineView):def __init__(self):QWebEngineView.__init__(self)文件路径 = os.path.abspath(os.path.join(os.path.dirname(__file__), 'form.html'))self.load(QUrl.fromLocalFile(filepath))self.loadFinished.connect(self._on_load_finished)def _on_load_finished(self):self.page().runJavaScript("document.getElementById('num1').value", self.store_value)def store_value(self, param):self.value = 参数打印(参数:" +str(参数))如果 __name__ == "__main__":app = QApplication(sys.argv)网页 = 网页()网络秀()sys.exit(app.exec_())HTML:<身体><表格>数字 1:<br>数字 2:<br><input type="submit" id="sub1"></表单> 解决方案 基于我在 我的旧答案中使用的策略,解决办法是通过QWebChannel注入一个QObject,并在其中绑定按钮点击事件来更新一个slot.在这种情况下,我使用 Jinja2 来简化脚本的编写.import os导入系统从 PyQt5 导入 QtCore、QtWidgets、QtWebEngineWidgets、QtWebChannel从 jinja2 导入模板类元素(QtCore.QObject):def __init__(self, name, parent=None):super(Element, self).__init__(parent)self._name = 姓名@财产定义名称(自己):返回 self._name定义脚本(自我):引发 NotImplementedError类 FormObject(Element):numbersChanged = QtCore.pyqtSignal(str, str)定义脚本(自我):_script = r"""var btn = document.getElementById('sub1');btn.addEventListener("点击", function(event){var number1 = document.getElementById('num1');var number2 = document.getElementById('num2');{{name}}.update(number1.value, number2.value);});"""返回模板(_script).render(name=self.name)@QtCore.pyqtSlot(str, str)定义更新(自我,编号1,编号2):self.numbersChanged.emit(number1, number2)类 WebEnginePage(QtWebEngineWidgets.QWebEnginePage):def __init__(self, *args, **kwargs):super(WebEnginePage, self).__init__(*args, **kwargs)self.loadFinished.connect(self.onLoadFinished)self._objects = []def add_object(self, obj):self._objects.append(obj)@QtCore.pyqtSlot(bool)def onLoadFinished(self, ok):如果没问题:self.load_qwebchannel()self.load_objects()def load_qwebchannel(self):file = QtCore.QFile(":/qtwebchannel/qwebchannel.js")如果 file.open(QtCore.QIODevice.ReadOnly):内容 = file.readAll()文件.close()self.runJavaScript(content.data().decode())如果 self.webChannel() 是 None:频道 = QtWebChannel.QWebChannel(self)self.setWebChannel(频道)def load_objects(self):如果 self.webChannel() 不是 None:objects = {obj.name: obj for obj in self._objects}self.webChannel().registerObjects(objects)_script = r"""{% for obj in objects %}var {{obj}};{% 结束为 %}新 QWebChannel(qt.webChannelTransport, 函数 (channel) {{% for obj in objects %}{{obj}} = channel.objects.{{obj}};{% 结束为 %}});"""self.runJavaScript(Template(_script).render(objects=objects.keys()))对于 self._objects 中的 obj:如果是实例(对象,元素):self.runJavaScript(obj.script())类网页(QtWebEngineWidgets.QWebEngineView):def __init__(self, parent=None):super().__init__(parent)页面 = WebEnginePage(self)self.setPage(页面)formobject = FormObject("formobject", self)formobject.numbersChanged.connect(self.on_numbersChanged)page.add_object(formobject)文件路径 = os.path.abspath(os.path.join(os.path.dirname(__file__), "form.html"))self.load(QtCore.QUrl.fromLocalFile(filepath))@QtCore.pyqtSlot(str, str)def on_numbersChanged(self, number1, number2):打印(编号1,编号2)如果 __name__ == "__main__":app = QtWidgets.QApplication(sys.argv)网页 = 网页()网络秀()sys.exit(app.exec_())I have a form.html file and i run it using PyQt5 QWebEngineView.I want to retrieve form values after the Submit button is clicked. I've gone through many solutions but cannot find the perfect one.Eg: I found this one but it works on URL Change.I'm just simply looking for a solution which works on clicking the Submit button.Here's my code that i have used from the above link but i'm not getting any value returned from the form:import osimport sysfrom PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidgetfrom PyQt5.QtCore import QUrl, QEventLoopfrom PyQt5.QtWebEngineWidgets import QWebEngineViewfrom PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptorclass WebPage(QWebEngineView): def __init__(self): QWebEngineView.__init__(self) filepath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'form.html')) self.load(QUrl.fromLocalFile(filepath)) self.loadFinished.connect(self._on_load_finished) def _on_load_finished(self): self.page().runJavaScript("document.getElementById('num1').value", self.store_value) def store_value(self, param): self.value = param print("Param: " +str(param))if __name__ == "__main__": app = QApplication(sys.argv) web = WebPage() web.show() sys.exit(app.exec_())HTML:<html> <body> <form> Number 1:<input type="text" id="num1"> <br> Number 2:<input type="text" id="num2"> <br> <input type="submit" id="sub1"> </form> </body></html> 解决方案 Based on the strategy that I used in my old answer, the solution is to inject a QObject through QWebChannel, and in it to make a binding with the button click event to update a slot. In this case I use Jinja2 to make writing the script easier.import osimport sysfrom PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannelfrom jinja2 import Templateclass Element(QtCore.QObject): def __init__(self, name, parent=None): super(Element, self).__init__(parent) self._name = name @property def name(self): return self._name def script(self): raise NotImplementedErrorclass FormObject(Element): numbersChanged = QtCore.pyqtSignal(str, str) def script(self): _script = r""" var btn = document.getElementById('sub1'); btn.addEventListener("click", function(event){ var number1 = document.getElementById('num1'); var number2 = document.getElementById('num2'); {{name}}.update(number1.value , number2.value); }); """ return Template(_script).render(name=self.name) @QtCore.pyqtSlot(str, str) def update(self, number1, number2): self.numbersChanged.emit(number1, number2)class WebEnginePage(QtWebEngineWidgets.QWebEnginePage): def __init__(self, *args, **kwargs): super(WebEnginePage, self).__init__(*args, **kwargs) self.loadFinished.connect(self.onLoadFinished) self._objects = [] def add_object(self, obj): self._objects.append(obj) @QtCore.pyqtSlot(bool) def onLoadFinished(self, ok): if ok: self.load_qwebchannel() self.load_objects() def load_qwebchannel(self): file = QtCore.QFile(":/qtwebchannel/qwebchannel.js") if file.open(QtCore.QIODevice.ReadOnly): content = file.readAll() file.close() self.runJavaScript(content.data().decode()) if self.webChannel() is None: channel = QtWebChannel.QWebChannel(self) self.setWebChannel(channel) def load_objects(self): if self.webChannel() is not None: objects = {obj.name: obj for obj in self._objects} self.webChannel().registerObjects(objects) _script = r""" {% for obj in objects %} var {{obj}}; {% endfor %} new QWebChannel(qt.webChannelTransport, function (channel) { {% for obj in objects %} {{obj}} = channel.objects.{{obj}}; {% endfor %} }); """ self.runJavaScript(Template(_script).render(objects=objects.keys())) for obj in self._objects: if isinstance(obj, Element): self.runJavaScript(obj.script())class WebPage(QtWebEngineWidgets.QWebEngineView): def __init__(self, parent=None): super().__init__(parent) page = WebEnginePage(self) self.setPage(page) formobject = FormObject("formobject", self) formobject.numbersChanged.connect(self.on_numbersChanged) page.add_object(formobject) filepath = os.path.abspath( os.path.join(os.path.dirname(__file__), "form.html") ) self.load(QtCore.QUrl.fromLocalFile(filepath)) @QtCore.pyqtSlot(str, str) def on_numbersChanged(self, number1, number2): print(number1, number2)if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) web = WebPage() web.show() sys.exit(app.exec_()) 这篇关于PyQt5 使用 runJavaScript 检索表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-26 15:14