Java教程

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>

结果

在这里插入图片描述

这篇关于PyQt5最全68 Web之PyQt5调用JavaScript代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!