编程语言
首页 > 编程语言> > PyQt5最全68 Web之PyQt5调用JavaScript代码

PyQt5最全68 Web之PyQt5调用JavaScript代码

作者:互联网

PyQt5最全68 Web之PyQt5调用JavaScript代码

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
import sys
import os


class WebEngineView(QWidget):
    """
    PyQt5调用JavaScript代码
    PyQt5和JavaScrip交互

    什么叫交互
    PyQt5<->JavaScript 即互相调用内部的函数
    """

    def __init__(self):
        super(WebEngineView, self).__init__()
        self.setWindowTitle('PyQt5调用JavaScript')
        self.setGeometry(5, 30, 1355, 730)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.browser = QWebEngineView()
        url = os.getcwd() + '/pyqt5calljs.html'
        self.browser.load(QUrl.fromLocalFile(url))
        self.layout.addWidget(self.browser)

        button = QPushButton('设置全名')
        button.clicked.connect(self.fullname)
        self.layout.addWidget(button)

    # 接受js返回值 即pyqt5calljs.html文件中的fullname函数返回值
    def js_callback(self, result):
        print(result)

    def fullname(self):
        self.value = 'hello world'
        self.browser.page().runJavaScript('fullname("' + self.value + '");', self.js_callback)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = WebEngineView()
    print(main.__doc__)
    main.show()
    sys.exit(app.exec_())

对应的pyqt5calljs.html文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试页面</title>
    <script>
        function fullname(value){
            alert("<" + value + ">")
            var firstname = document.getElementById('firstname').value;
            var lastname = document.getElementById('lastname').value;
            var fullname = firstname + ' ' + lastname
            document.getElementById('fullname').value = fullname;
            document.getElementById('submit-btn').style.display = 'block';
            return fullname;
        }
    </script>
</head>
<body>
    <form>
        <label>First Name:</label>
        <input type="text" name="firstname" id="firstname"></input>
        <br/>
        <label>Last Name:</label>
        <input type="text" name="lastname" id="lastname"></input>
        <br/>
        <label>Full Name:</label>
        <input type="text" name="fullname" id="fullname"></input>
        <br/>
        <input  style="display:none;" type="submit" id="submit-btn"/>
    </form>
</body>
</html>

结果

在这里插入图片描述

标签:__,Web,self,JavaScript,PyQt5,value,import,fullname
来源: https://blog.csdn.net/m0_63993933/article/details/121938355