PyQt5 Quick Start (seven) PyQt5 extension

PyQt5 Quick Start (seven) PyQt5 extension

A, PyQt5 Project Releases

1, PyInstaller Profile

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

2, PyInstaller use

PyInstaller use the command is as follows:
pyinstaller yourprogram.py
the need to switch to the file directory xxx.py PyInstaller used.
Common options are as follows:
-F: After packing generate only a single executable file
-D: the default options, create a directory that contains the executable files, and rely heavily on file
-c: the default option, use the console
-w: do not use the console
-p: Add search path, let it find the corresponding library
-i: change icon icon generating program.

3, PyInstaller principle

PyInstaller the Python interpreter and the Python script packaged into a single executable file, and not compiled into machine code. PyInstaller packed executable file does not improve operational efficiency, and may reduce operating efficiency. The advantage is packaged in the operation of the machine without installing Python and Python scripts rely on libraries. In the Linux system, PyInstaller mainly used binutil Kit ldd and objdump command.
PyInstaller analyzes specified Python script relies on other dependent, then find and copy, all dependencies are collected and encrypted, including the Python interpreter, and finally packaged files to a directory or packed into the executable file .
Use PyInstaller package generated executable file, can only run in the same environment and packaging machines, if you want to run on different operating systems, must be repackaged in the new operating system environment.

Second, interactive web pages

1, QWebEngineView Profile

PyQt5 use QWebEngineView to display HTML pages, WebEngine is based on Google Chromium engine development, PyQt5 can be used PyQt5.QtWebKitWidgets.QWebEngineView to use web control.
QWebEngineView using load (QUrl url) to load the specified URL given display, setHtml (QString & html) is used to view a content page to the specified HTML content.
QWebEngineView use load to load a Web page, the actual Web page is loaded using the HTTP GET method.

2, load external display 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 a 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 call JavaScript code

May conveniently be achieved by the QWebEnginePage runJavaScript (str, callable) PyQt5 and bidirectional communication HTMP / JavaScript, to achieve the Python code and decoupling HTMP / JavaScript code developers to facilitate the division of labor,

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('设置全名')
        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__":
    # 创建一个 application实例
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

6, JavaScript code that calls PyQt5

JavaScript code that refers to PyQt PyQt call can be two-way data exchange with the loaded Web page. First, the use of QWebEngineView object to load Web pages can obtain the page form input data, collect data through user-submitted JavaScript code in Web pages. Then, in the Web page, JavaScript data transmitted through a bridge connection to PyQt. PyQt received Web data transfer, after service processing, the data after the processing is returned to the Web page.
(1) create QWebChannel objects
created QWebChannel objects, registering a need to bridge the object to a Web page using JavaScript.
= QWebChannel Channel ()
obj = ClassName ()
channel.registerObject ( "Bridge", obj)
view.page (). setWebChannel (Channel)
(2) create PyQt shared data objects
created shared objects need 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)

    # 需要定义对外发布的方法
    strValue = pyqtProperty(str, fget=_g
```etStrValue, fset=_setStrValue)

(3)创建调用PyQt的Web页面
在Web页面访问PyQt中注册的对象,获得channel.objects.bridge共享对象,bridge是在PyQt中注册共享对象时指定的名称,核心代码如下:

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

new QWebChannel(qt.webChannelTransport, function(channel){
    window.bridge = channel.objects.bridge;
    alert('bridge=' + bridge + '\n从pyqt传来的参数=' + window.bridge.strValue);
});

});

Guess you like

Origin blog.51cto.com/9291927/2424319