Hello PyQt5PyQt5 extension

Posted by ThatGuyBob on Thu, 24 Feb 2022 17:26:14 +0100

1, PyQt5 project release

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 XXX The directory where the PY file is located.

Common options are as follows:

-F: Only a single executable 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, use console

-w: Do not use console

-p: Add a search path to find the corresponding library

-i: Change the icon icon of the generator.

3. PyInstaller principle

PyInstaller packages Python interpreter and python script into an executable file, which is not compiled into machine code. The executable packaged by PyInstaller will not improve the operation efficiency, and may reduce the operation efficiency. The advantage of packaging is that you don't have to install Python and the libraries that Python scripts depend on on on the running machine. Under Linux system, PyInstaller mainly uses ldd and objdump commands in binutil toolkit.

PyInstaller will analyze other dependencies that the specified Python script depends on, then find and copy them, collect and encrypt all dependencies, including Python interpreter, and finally package the files into a directory or executable file.

The executable generated by packaging with PyInstaller can only run in the same environment as the packaging machine. If you want to run on a different operating system, you must repack it in the new operating system environment.

2, Web interaction

1. Introduction to QWebEngineView

PyQt5 uses QWebEngineView to display HTML pages. WebEngine is developed based on Google Chrome engine. PyQt5 can be used in PyQt5 QtWebKitWidgets. QWebEngineView to use web page controls.

QWebEngineView uses load(QUrl url) to load the specified URL, and setHtml (qstring & html) is used to set the content of the web page view to the specified HTML content.

QWebEngineView uses load to load a Web page. In fact, it uses HTTP GET method to load a Web page.

2. Load and display 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. Load local Web page

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. Load and display 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 runJavaScript (str, callable) of QWebEnginePage can easily realize the two-way communication between PyQt5 and HTMP/JavaScript, realize the decoupling of Python code and HTMP/JavaScript code, and facilitate the division and cooperation of 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 conduct two-way data interaction with the loaded Web page. First, after loading the Web page with the QWebEngineView object, you can obtain the form input data in the page, and collect the data submitted by the user through JavaScript code in the Web page. Then, in the Web page, JavaScript passes data to PyQt through bridge connection. PyQt receives the data transmitted from the Web and returns the processed data to the Web page after business processing.

(1) Create QWebChannel object

Create a QWebChannel object and register an object that needs to be bridged so that the JavaScript of the Web page can be used.

channel = QWebChannel()
obj = ClassName()
channel.registerObject("bridge", obj)
view.page().setWebChannel(channel)

(2) Create PyQt objects that share data

The created shared object needs to inherit from QWidget or QObject.

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)

    # You need to define the method of publishing
    strValue = pyqtProperty(str, fget=_getStrValue, fset=_setStrValue)

(3) Create a Web page that calls PyQt

Access the object registered in PyQt on the Web page to obtain 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 Parameters passed=' + window.bridge.strValue);
    });
});

Topics: Qt PyQt5