PyQt5 Quick Start PyQt5 Extension

Keywords: Python Javascript Linux Windows

PyQt5 Quick Start (VII) PyQt5 Extension

I. Publication of PyQt5 Project

1. Introduction to PyInstaller

PyInstaller is a free and easy-to-use packaging tool that supports Windows, Linux, MacOS and 32-bit and 64-bit systems.
http://www.pyinstaller.org/
PyInstaller installation:
pip install pyinstaller

2. PyInstaller uses

PyInstaller uses the following commands:
pyinstaller yourprogram.py
When using PyInstaller, you need to switch to the directory where the xxx.py file is located.
Common options are as follows:
- F: Only a single executable file is generated after packaging
- D: The default option is to create a directory containing executable files and a large number of dependent files.
- c: Default option, using console
- w: No console
- p: Add a search path to find the corresponding library
- i: Change the icon icon of the generator.

3. PyInstaller Principle

PyInstaller packages the Python interpreter and Python script into an executable file and does not compile it into machine code. PyInstaller packaged executable files will not improve the efficiency of operation, and may reduce the efficiency of operation. The advantage of packaging is that you don't have to install libraries that Python and Python scripts rely on on on the running machine. Under Linux, PyInstaller mainly uses ldd and objdump commands in the binutil toolkit.
PyInstaller will analyze the other dependencies on which the specified Python script depends, find and copy them, collect all the dependencies and encrypt them, including the Python interpreter, and finally pack the files into a directory or into an executable file.
Executable files packaged with PyInstaller can only run in the same environment as the packaged machine. If they are to run on different operating systems, they must be repackaged in the new operating system environment.

II. Web page interaction

1. Introduction to QWeb EngineView

PyQt5 uses QWeb EngineView to display HTML pages. Web Engine is developed based on Google Chromium engine. PyQt5 can use PyQt5.QtWebKitWidgets.Q WebEngine View to use web page controls.
QWeb EngineView uses load(QUrl url) to load the specified URL to specify the display, and setHtml (QString & html) is used to set the content of the page view to the specified HTML content.
QWeb EngineView uses load to load a Web page. In fact, it uses HTTP GET to load a Web page.

2. Loading and displaying external Web pages

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

class MainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.browser = self.browser = QWebEngineView()
        self.layout.addWidget(self.browser)
        self.setLayout(self.layout)
        self.browser.load(QUrl("http://www.51cto.com/"))

        self.setWindowTitle("HuaWei Web")
        self.setGeometry(5, 30, 1355, 730)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

3. Loading local Web pages

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

class MainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.browser = self.browser = QWebEngineView()
        self.layout.addWidget(self.browser)
        self.setLayout(self.layout)
        self.browser.load(QUrl(r"/home/user/PyQt.html"))

        self.setWindowTitle("Local HTML")
        self.setGeometry(5, 30, 1355, 730)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

4. Loading and displaying embedded HTML code

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

class MainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.browser = self.browser = QWebEngineView()
        self.layout.addWidget(self.browser)
        self.setLayout(self.layout)
        self.browser.setHtml('''
                            <!DOCTYPE html>
                            <html>
                            <head>
                           <meta charset="UTF-8">
                           <title>PyQt5</title>
                            </head>
                           <body>
                              <h1>hello PyQt5</h1>
                              <h2>hello PyQt5<h2>
                           </body>
                            </html>
                            ''')

        self.setWindowTitle("Local HTML")
        self.setGeometry(5, 30, 1355, 730)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

5. PyQt5 calls JavaScript code

The two-way communication between PyQt5 and HTMP/JavaScript can be easily realized by using runJavaScript (str, callable) of QWeb EnginePage. The decoupling of Python code and HTMP/JavaScript code is realized, which facilitates the division of work and cooperation among developers.

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys

html = '''
      <html>
        <head>
          <title>A Demo Page</title>
          <script language="javascript">
            // Completes the full-name control and
            // shows the submit button
            function completeAndReturnName() {
              var fname = document.getElementById('fname').value;
              var lname = document.getElementById('lname').value;
              var full = fname + ' ' + lname;
              document.getElementById('fullname').value = full;
              document.getElementById('submit-btn').style.display = 'block';
              return full;
            }
          </script>
        </head>
        <body>
          <form>
            <label for="fname">First name:</label>
            <input type="text" name="fname" id="fname"></input>
            <br />
            <label for="lname">Last name:</label>
            <input type="text" name="lname" id="lname"></input>
            <br />
            <label for="fullname">Full name:</label>
            <input disabled type="text" name="fullname" id="fullname"></input>
            <br />
            <input style="display: none;" type="submit" id="submit-btn"></input>
          </form>
        </body>
      </html>
    '''

class MainWindow(QWidget):
    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)
        self.result = None
        self.layout = QVBoxLayout()
        self.webView = QWebEngineView()
        self.webView.setHtml(html)
        self.layout.addWidget(self.webView)
        button = QPushButton('Set Full Name')
        self.layout.addWidget(button)
        self.setLayout(self.layout)
        self.resize(400, 200)
        self.setWindowTitle("PyQt JS")
        button.clicked.connect(self.complete_name)

    def complete_name(self):
        self.webView.page().runJavaScript('completeAndReturnName();', self.js_callback)

    def js_callback(self, result):
        self.result = result
        print(result)

if __name__ == "__main__":
    # Create an application instance
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

6. JavaScript calls PyQt5 code

JavaScript calling PyQt code means that PyQt can interact bidirectionally with loaded Web pages. First, after loading the Web page with the QWeb EngineView object, you can get the form input data in the page, and collect the data submitted by users through JavaScript code in the Web page. Then, in Web pages, JavaScript passes data to PyQt through bridge connections. PyQt receives the data transmitted by the Web, and after business processing, returns the processed data to the Web page.
(1) Create QWebChannel objects
Create a QWebChannel object and register an object that needs to be bridged for JavaScript use on Web pages.
channel = QWebChannel()
obj = ClassName()
channel.registerObject("bridge", obj)
view.page().setWebChannel(channel)
(2) Create PyQt objects that share data
Shared objects created need to be inherited from QWidget s or QObject s.

from PyQt5.QtCore import QObject
from PyQt5.QtCore import pyqtProperty
from PyQt5.QtWidgets import QWidget, QMessageBox

class SharedObject(QWidget):

    def __init__(self):
        super(SharedObject, self).__init__()

    def _getStrValue(self):
        #
        return '100'

    def _setStrValue(self, str):
        # get web parameter
        print("web parameter: ", str)

    # Need to define methods for external Publishing
    strValue = pyqtProperty(str, fget=_g
```etStrValue, fset=_setStrValue)

(3)Create calls PyQt Of Web page
//Access the object registered in PyQt on the Web page and get the channel.objects.bridge shared object. bridge is the name specified when registering the shared object in PyQt. The core code is as follows:

document.addEventListener("DOMContentLoaded", function()
{

new QWebChannel(qt.webChannelTransport, function(channel){
    window.bridge = channel.objects.bridge;
    alert('bridge=' + bridge + '\n from pyqt Passed parameters=' + window.bridge.strValue);
});

});

Posted by PandaFi on Sun, 28 Jul 2019 04:18:47 -0700