程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python qtgui and data visualization programming (I) do you want to write GUI programs? Try Python QT!

編輯:Python

Author's brief introduction : Hello everyone, I am the five-dimensional sky , At present, he is a member of a state-owned enterprise Java Full stack programmer , Love technology 、 Like code , I hope my article can bring you harvest .

Personal home page : Five dimensional starry csdn Blog

Series column :Python QtGUI And visual programming

If you think the blogger's article is good , Please support the blogger for the third company !
Or wechat search “ Five dimensional sky ” Pay attention to me ~
Bibliography :《Python QtGUI And data visualization programming 》

1. PyQt Development environment construction

1.1 Python install

Click the link to download directly Python3.10 edition :https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe

Download too slow ? WeChat search “ Five dimensional sky ”, send out “python Installation package ” Get the network disk download address .

After downloading, double-click to start the installer ( Remember to check add to path).

1.2 PyQt5 install

open cmd perform pip3 install pyqt5.

It's slow ? The source changing method is sent to . The following command is to replace it with the source of the University of science and technology of China .

pip install pip -U # upgrade 
pip config set global.index-url https://pypi.mirrors.ustc.edu.cn/simple/ # Source change 

1.3 Qtdesigner install

This thing is mainly used to design interfaces , you 're right , Drag and drop controls to generate interfaces , Then execute the command to convert it to Python Code .( Big guys who like to knock with their hands can skip this tool ,over~)

Click the link to download directly Qtdesigner Windows edition :https://build-system.fman.io/static/public/files/Qt%20Designer%20Setup.exe

And slow ? WeChat search “ Five dimensional sky ”, send out “QtDesigner Installation package ” Get the network disk download address .

After downloading, double-click to start the installer .

2. PyQt Development infrastructure

2.1 The first program ——HelloWorld

The foundation is not solid 、 Grammar does not ?** No big problem . Chairman Mao said , Practice is the only criterion for testing truth .** To write a HelloWorld Well

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == '__main__':
# establish APP
app = QtWidgets.QApplication(sys.argv)
# Create a form 
mainFrame = QtWidgets.QWidget()
# Set the window size 
mainFrame.resize(800, 200)
# Set the title of the form 
mainFrame.setWindowTitle("HelloWorld")
# take Label Components are bound to mainFrame On , And set the content 
labelHello = QtWidgets.QLabel(mainFrame)
labelHello.setText("Hello World!By Five dimensional sky ~")
# Set the font 
font = QtGui.QFont()
# Bold font 
font.setBold(True)
# font size 
font.setPixelSize(26)
labelHello.setFont(font)
# Calculation Label And return QSize object 
size = labelHello.sizeHint()
# Set up labelHello Coordinates, width and height of 
labelHello.setGeometry(250, 100, size.width(), size.height())
# Display dialog box at runtime 
mainFrame.show()
# Start the application 
sys.exit(app.exec_())

Running results :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nkfS12K4-1655217489235)(D:\WorkSpace\markdown\ book \image\image-20220604100945081.png)]

2.2 Use QtDesigner Design form

​ stay 2.1 We wrote a simple HelloWorld Program ( I don't understand ? No big problem , You can understand it by knocking at the back ), In this section we use QtDesigner To do the same thing . Before that , Let's take a brief look at the following picture QtDesigner The interface of .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-THJKQHan-1655217489236)(D:\WorkSpace\markdown\ book \image\image-20220604104550848.png)]

Okay , Now let's start this section .

  1. open QtDesigner, Create the program according to the following figure .

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-mGwE7yey-1655217489237)(D:\WorkSpace\markdown\ book \image\image-20220604101808796.png)]

  2. find windowTitle attribute , Enter the window title

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-9yLICjgD-1655217489237)(D:\WorkSpace\markdown\ book \image\image-20220604101951714.png)]

  3. find Label Components , Drag to the form location

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-RFmrZ1b1-1655217489238)(D:\WorkSpace\markdown\ book \image\image-20220604102127120.png)]

  4. Double click to enter editing mode , Input HelloWorld! By Five dimensional sky ~, Adjust to fit .

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-4Cz3dnTc-1655217489238)(D:\WorkSpace\markdown\ book \image\image-20220604102301486.png)]

  5. Select... In the object browser on the right label, Then find in the Attribute Editor font attribute , Choose the right font ( Cough , Commercial users should pay attention to font infringement ~), Remember to adjust the font size after setting it Label size .

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-KAt4FsUG-1655217489239)(D:\WorkSpace\markdown\ book \image\image-20220604102742568.png)]

    Commercially available Fonts ( Talk about the arrangement : Search results come from the Internet ,“ Five dimensional sky ” Is not responsible for the accuracy of the results ~):

    1. Siyuan font , The free commercial ones are : Ses blackbody , Siyuan Songti , Siyuan soft blackbody .

    2. Founder font , Founder typefaces can be used commercially for free : Founder imitation song dynasty style typeface ( Jane , Numerous ), Founder blackbody ( Jane , Numerous ), Regular script founder ( Simple and complicated ), Founder book-maker song ( Jane , Numerous ).

  6. forehead , Forgot to resize the form , Make up make up ~

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-oLisKWoZ-1655217489240)(D:\WorkSpace\markdown\ book \image\image-20220604103331425.png)]

  7. adjustment Label size

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-IIZ9KZQR-1655217489240)(D:\WorkSpace\markdown\ book \image\image-20220604103717693.png)]

  8. Ctrl+S Save the generated helloWorld.ui File can .

  9. stay helloWorld.ui Open in file directory cmd, Input pyuic5 -o ui_HelloWorld.py helloWorld.ui Generate after carriage return python file .

    pyuic5 yes PyQt5 The tool software , stay 1.2 Subsection installation PyQt5 It has been installed in D:\Software\Python310\Scripts Under the path ( Note that this is my local path , Your path should be yours Python Installation position .)

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-D5sJ9r4Y-1655217489241)(D:\WorkSpace\markdown\ book \image\image-20220604105000176.png)]

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-OrtZ4Slc-1655217489241)(D:\WorkSpace\markdown\ book \image\image-20220604105056282.png)]

    common problem :

    1. pyuic5 The command does not exist ?

      one's junior of equal standing , Did you forget to add environment variables ? Remember to restart after adding cmd window .

      [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TBGFwt20-1655217489242)(D:\WorkSpace\markdown\ book \image\image-20220604105612257.png)]

    2.3 Use QtDesigner Design interface

    ​ stay 2.1 Section we use QtDesigner It generates a HelloWorld Program and convert it into python Code , In this section, we will learn how to use this code . Is there a partner who has run the code and found nothing to happen ? Don't panic , Let's move on . Let's take a brief look at the contents of this document .

    # -*- coding: utf-8 -*-
    # Form implementation generated from reading ui file 'helloWorld.ui'
    #
    # Created by: PyQt5 UI code generator 5.15.6
    #
    # WARNING: Any manual changes made to this file will be lost when pyuic5 is
    # run again. Do not edit this file unless you know what you are doing.
    from PyQt5 import QtCore, QtGui, QtWidgets
    class Ui_Form(object):
    ''' Be careful , Inherited here is object Object instead of QWidget object '''
    def setupUi(self, Form):
    ''' Set up ui Function of ,Form Container object for the outermost component of the program '''
    Form.setObjectName("Form") # Set up Form Object name 
    Form.resize(800, 200) # Set size 
    self.label = QtWidgets.QLabel(Form) # stay Form Define a Label
    self.label.setGeometry(QtCore.QRect(250, 100, 420, 35)) # Definition Label Location 
    font = QtGui.QFont() # Define the font 
    font.setFamily(" Regular script ")
    font.setPointSize(26)
    font.setBold(True)
    font.setWeight(75)
    self.label.setFont(font) # Set up Label typeface 
    self.label.setTextFormat(QtCore.Qt.AutoText) # format processing 
    self.label.setObjectName("label") # Set up Label Object name 
    self.retranslateUi(Form) # Custom method 
    QtCore.QMetaObject.connectSlotsByName(Form) # Associate signals with slots by name 
    def retranslateUi(self, Form):
    ''' Set up Form Of UI attribute '''
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "HelloWorld"))
    self.label.setText(_translate("Form", "HelloWorld! By Five dimensional sky ~"))
    

    What about? ? Is it similar to our handwritten code , The signal and slot section will be discussed later , You only need to understand the style of this document (QtDesigner There will be an inheritance object Class of ui Some of the settings for ).

    There are three common ways to use this code file .

    1. Mode one : direct method ( Not recommended )

      import sys
      from PyQt5 import QtCore, QtGui, QtWidgets
      from ui_HelloWorld import Ui_Form
      if __name__ == '__main__':
      app = QtWidgets.QApplication(sys.argv)
      container = QtWidgets.QWidget()
      form = Ui_Form()
      form.setupUi(container) # Pass the outermost component container object into 
      container.show()
      sys.exit(app.exec_())
      

      shortcoming : Coupling too high .

    2. The way 2: Multiple inheritance ( Not recommended )

      import sys
      from PyQt5.QtWidgets import QApplication, QWidget
      from ui_HelloWorld import Ui_Form
      class MyWidget(QWidget, Ui_Form):
      """ Multiple inheritance """
      def __init__(self):
      # When multiple inheritance ,super() Is the first base class , Here is QWidget.
      super().__init__() # Call parent constructor , Create a form .
      self.labTip = " Multiple inheritance " # Define a new variable 
      self.setupUi(self) # The current class (QWidget Subclasses of ) Pass in 
      self.label.setText(self.labTip) # Set up label Content 
      if __name__ == '__main__':
      app = QApplication(sys.argv)
      container = MyWidget()
      container.show()
      sys.exit(app.exec_())
      

      shortcoming :MyWidget Own attributes and Ui_Form The properties of are mixed together , Hard to distinguish .

    3. The way 3: Single inheritance ( recommend

    import sys
    from PyQt5.QtWidgets import QApplication, QWidget
    from ui_HelloWorld import Ui_Form
    class MyWidget(QWidget):
    """ Single inheritance """
    def __init__(self, parent=None):
    super().__init__(parent) # Call parent constructor , Create a form 
    self.__ui = Ui_Form() # establish ui object 
    self.__ui.setupUi(self) # Set the parent form 
    self.labTip = " Single inheritance " # Custom properties 
    self.__ui.label.setText(self.labTip) # Set up ui Internal properties 
    if __name__ == '__main__':
    app = QApplication(sys.argv)
    container = MyWidget()
    container.show()
    sys.exit(app.exec_())
    

    advantage :MyWidget Own attributes and Ui_Form The properties of are easy to distinguish .

    The font shows the problem partner , Please put ui Transferred python In the document font.setPointSize(26) Change it to font.setPixelSize(26).QtDesigner There is no setPixelSize attribute , Should be QtDesigner and python It is caused by version inconsistency , The specific reason is not deep , Interested friends can discuss in the comment area .

I am a five-dimensional sky , a Java Full stack developer , Love technology , Thank you for your great praise 、 Collections and reviews , See you next time !

WeChat search “ Five dimensional sky ” Pay attention to me ~

by Five dimensional sky - Share front and rear technologies


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved