python - 从js QWebEngineView获取变量到python

标签 python pyqt5 qt-designer qwebengineview

从js QWebEngineView获取变量到python。

我正在使用 PyQt5 和 python3 的 QT Designer,并且使用 QWebEngineView 来加载 html 和 js。 html 内部有一个输入和一个按钮,按下按钮会执行一个 js 函数,该函数将输入的值保存在变量中。

如何从 js 中获取该变量并转到 python?

HTML 代码:

<input id="input">
<button id="button" onclick="x()"></button>
<script>
function x() {
    var a = document.getElementById("input").value;
}
</script>

Python 代码:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(449, 391)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        Form.setWindowOpacity(0.8)
        self.webEngineView = QtWebEngineWidgets.QWebEngineView(Form)
        self.webEngineView.setGeometry(QtCore.QRect(-1, 0, 451, 391))
        self.webEngineView.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.webEngineView.setStyleSheet("width: 100%")
        self.webEngineView.setUrl(QtCore.QUrl("file:///C:/xampp/htdocs/indexx.html"))
        self.webEngineView.setObjectName("webEngineView")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Bancus"))
from PyQt5 import QtWebEngineWidgets

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

最佳答案

你的问题的描述不清楚,但假设你想在按下按钮时将文本放入Python的输入中,并且你可以修改HTML,那么一个可能的解决方案是使用QWebChannel:

from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel


class Backend(QtCore.QObject):
    valueChanged = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self._value = ""

    @QtCore.pyqtProperty(str)
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        self._value = v
        self.valueChanged.emit(v)


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.webEngineView = QtWebEngineWidgets.QWebEngineView()
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.webEngineView, stretch=1)
        lay.addWidget(self.label, stretch=1)

        backend = Backend(self)
        backend.valueChanged.connect(self.label.setText)
        backend.valueChanged.connect(self.foo_function)
        self.channel = QtWebChannel.QWebChannel()
        self.channel.registerObject("backend", backend)
        self.webEngineView.page().setWebChannel(self.channel)

        path = "C:/xampp/htdocs/indexx.html"
        self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(path))

    @QtCore.pyqtSlot(str)
    def foo_function(self, value):
        print(value)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>        
        <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    </head>
    <body> 
         <input id="input">
         <button id="button">Click me</button>
    </body>
    <script>
        var backend = null;
        new QWebChannel(qt.webChannelTransport, function (channel) {
            backend = channel.objects.backend;
        });
        document.getElementById("button").addEventListener("click", function(){
            backend.value = document.getElementById("input").value;
        });
    </script>
</html>

如果我的假设有错误,请随时指出以提供合适的解决方案。

关于python - 从js QWebEngineView获取变量到python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58940974/

相关文章:

javascript - 与 Django 配合良好的用于表单验证的最佳 JQuery 插件是什么?

python - 无法使用钟摆来解析系列中的日期,但可以一一解析

python - 如何在 PyQT5 中为 QPlainTextEdit(或任何其他组件)实现关键监听器

c++ - QDial 更改位置指示器文本

python - 使 Python 脚本可执行 chmod755?

python - Pandas 错误 - 遇到无效值

Python Shell 在使用 PyQt5 的 while 循环后重新启动

python - 使用 Up-Down 键在元素间移动

python - 使用 python 为 Qt Designer 自定义 Qt 小部件

python - PyQt5 固定窗口大小