Python Xiaobai from scratch pyqt5 project actual combat (4) basic controls

youcans 2021-10-29 02:19:02
python xiaobai scratch pyqt5 pyqt

This series is for Python The small white , From scratch, practical interpretation application QtDesigner Conduct PyQt5 Project practice of .
What is starting from scratch ? Install... From software 、 Environment configuration start . Don't skip a detail , Don't miss a line of code , Do not omit an example diagram .
PyQt5 It provides rich input and output controls . This article introduces through QtDesigner Toolbar creates common basic controls , Includes various button controls 、 Text input control and adjustment input control .

Welcome to your attention 『Python Xiaobai starts from scratch PyQt5 Project practice @ Youcans』 series , Ongoing update
Python Xiaobai starts from scratch PyQt5 Project practice (1) Installation and environment configuration
Python Xiaobai starts from scratch PyQt5 Project practice (2) Menus and toolbars
Python Xiaobai starts from scratch PyQt5 Project practice (3) Signal to slot connection
Python Xiaobai starts from scratch PyQt5 Project practice (4) Basic controls



1. PyQt5 Control introduction

1.1 What are controls

Control is also called control object , yes Qt The most basic component type in the user interface , It is also the basic structure of the user interface . Everything displayed on the user interface is a control , For example, buttons 、 label 、 The text box , Another example is the menu bar 、 The toolbar 、 status bar , Even the entire window itself is a control .

QWidget Class is PyQt5 Base class of , It is also the parent of all controls . be-all Qt Controls are all QWidget Subclasses of classes , So they all inherited QWidget Class , Can receive user input events , Such as mouse and keyboard input , And can display the control content on the user interface , You can also store other controls .


1.2 Edit the properties of the control

Control has properties . Different types of controls have some of the same properties , It also has some different proprietary properties .

The same properties of the control include : name , shape , Location , size , Format . The special properties of the control include : Show content , Accept input , User interaction , date , frame , wait .

be-all Qt Controls are all QWidget Subclasses of classes , Inherited QWidget Attributes of a class . therefore , We can learn by class , First learn the general properties of its inherited parent class , Then learn the specific properties of the control . The learning of controls is the structure diagram of the inheritance relationship of a class .

We use a graphical interface uiDemo5.ui For example , Describes the general properties of the control , And edit and modify the properties of the control .

As mentioned earlier ,QtDesigner On the top right “ Object viewer ” Displays the control name and structure in the interface , At the bottom of the “ Property editor ” Displays various properties of the selected control object . Select a control in the graphical interface , Or in “ Object viewer ” Select a control in the , stay " Property editor " The properties of the control object will be displayed .

 Insert picture description here


Whether it's a window object MainWindow、 menu bar menubar、 The toolbar toolBar, Or button pushButton、 Edit line lineEdit, All have some of the same properties , for example :

  • objectName: Control name , It's very important . To be exact, it's the of the control ID,Python Access control in program 、 Controls interact using objectName. All controls must have a unique objectName, You can't have the same name . Chinese characters cannot be used .
  • geometry: Size and location of control .
    • The width and height of the control can be modified , about MainWindow For the width of the control / Height is the width of the GUI program window / Height .
    • Control location (X, Y) Is the coordinate value of the control in the window control ,MainWindow The location of the control cannot be modified , Location of other controls (X, Y) Can be modified as needed .
    • minimumSize、maximumSize Is the main window size after stretching , The minimum size of the control object 、 Maximum size .
  • font: Control to select the font to display , Including Fonts 、 Font size 、 style 、 Effects and other options .

1.3 PyQt5 Control type

To understand QtWidgets Subclasses of classes , have access to “subclasses()” Print out all subclasses , Co ownership 30 A subclass .

 import PyQt5
print(QtWidgets.QWidget.__subclasses__())

These control types , In general, it can be classified as follows :

  • Input control :

    • Button :QPushButton( Press the button ),QToolButton( Tool button ),QRadioButton( Radio buttons ),QCheckButton( Checkbox ),QCommandLinkButton( Button for connecting commands )
    • Keyboard input control :QlineEdit( Single line input ),QTextEdit( Multi line input ),QPlainTextEdit( Common multiline input ),QkeySequenceEdit( Shortcut key input )
    • Adjust the input control :QAbstractSpinBox( Step adjustment input ),QDateEdit( Date input ),QTimeEdit( Time input ),QDateTimeEdit( Date and time input )
    • Spin box control :QSpinBox( Integer digital adjustment frame ),QDoubleSpinBox( Floating point number adjustment box )
    • Slide the input control :QDial( Rotate drag slip input ),QSlider( Drag the input line ),QScrollBar( Scroll bar ),QRubberBand( Rubber band drag )
    • Drop down input control :QComboBox( Combo box drop-down options ),QSlider( Drag the input line ),QScrollBar( Scroll bar ),QRubberBand( Rubber band drag )
    • Dialog box input control :QDialog( Dialog box ),QColorDialog( Color dialog ),QFileDialog( File dialog ),QFontDialog( Font dialog ),QInputDialog( Input Dialog )
    • calendar control :QCalendarWidget( Date selection part )
  • Display controls :

    • Content display control :QLabel( Display box ),QLCDNumber( Liquid crystal display ),QProgressBar( Progress bar )
    • The dialog box displays the control :QMessageBox( Message box ),QErrorMessage( Error box ),QProgressDialog( Progress box )
  • Advanced controls :

    • Container controls :QToolBox,QDialogButtonBox,QGroupBox,QMdiSubWindow
    • Structure control :QMainWindow,QTabwidget,QStackedWidget,QSplitter,QDockWidget
    • Scroll controls :QTextBrowser,QScrollArea,QAbstractItemView,QMdiarea,QGraphicsView
    • Auxiliary control :QFocusFrame,QSizeGrip,QDesktopWidget
    • Other controls

stay QtDesigner Left side “WidgetBox” In the toolbar , Group commonly used controls by category . Drag the control icon in the toolbar to QtDesigner The middle graphical interface editing window , A selected control is created in the image interface .

 Insert picture description here



2. Button control

2.1 Introduction to button control

Buttons are the most commonly used control type .

stay QtDesigner Left side “WidgetBox” In the toolbar "Buttons" Group , There are many different types of button controls :PushButton( Press the button ),QToolButton( Tool button ),QRadioButton( Radio buttons ),QCheckButton( Checkbox ),QCommandLinkButton( Button for connecting commands ).QDialogButtonBox( Standard button box ) Provide a series of standard buttons , Equivalent to a combination of button controls .

Common properties of button controls :

  • text: Show text
  • icon: Set icon
  • iconSize: Icon size
  • shortcut: Set shortcut key
  • checkable: Set whether to switch the button automatically
  • checked: Set the default selection state
  • autoRepeat: Set whether to automatically repeat when the user presses
  • autoExclusive: Sets whether automatic exclusivity is enabled ( Set multiple selection boxes )

Signal trigger condition of button control :

  • clicked(): Signals when the button is first pressed and then released
  • clicked(bool): Signals when the button is first pressed and then released , And pass the current state to the outside world
  • pressed(): When the mouse cursor is inside the button , Press the left mouse button to send a signal
  • released(): Signal when the left mouse button is released
  • toggled(bool): Signal when the state of the button changes , And pass the current state to the outside world

Common modes for button controls / state :

  • Available or unavailable , When disabled, the button is grayed out
  • Standard button , Switch button or menu button
  • Turn on or off ( For switch buttons only )
  • Default state or normal state
  • Whether to automatically repeat
  • Whether it is pressed

Drag the button control in the toolbar to QtDesigner The middle graphical interface editing window , Just create a button control in the image interface . As shown in the figure below , We are in the graphical interface uiDemo5.ui The left side of the , Created several different button controls .

 Insert picture description here


2.2 Press the button (QPushButton)

QPushButton( Press the button ) Is the most commonly used button , Press down ( Or click ) Buttons can perform an action or answer a question , for example : determine , application , Cancel , close , yes , No and help .

Button controls usually display a text label (text), You can select an icon for the button (icon), You can also choose to set shortcut keys (shortcut).

The above properties of the key button , Can be in “ Property editor ” Edit and modify in the corresponding attribute line in .

When the key button is activated by the mouse or shortcut key , The button will sound clicked() The signal , You can trigger specific operations by connecting slot functions .


2.3 Other buttons

QToolButton( Tool button ) Often used in toolbars , Usually in the creation of QAction Instance . Tool buttons usually display an icon , You can quickly access specific commands or options .

QRadioButton( Radio buttons ) Is a radio box with a text label , Can open ( Choose ) Or turn off ( Not selected ). When the radio box is selected or cleared , Will send out “toggled()” The signal , You can trigger specific operations by connecting slot functions .

QCheckButton( Checkbox ) Is a check box with a text label , In addition to opening ( Choose ) Or turn off ( Not selected ), Semi selected status is also provided ( optional ). When the check box is selected or cleared , Will launch “stateChanged()” The signal , You can trigger specific operations by connecting slot functions .

The radio box defines “ A commonplace ” The choice of , And the check box provides “ More than a multiple-choice ” The choice of .

QCommandLinkButton( Button for connecting commands ) It looks like a flat QPushButton, And it comes with a right icon , Its purpose is similar to radio buttons , Used to select between a set of mutually exclusive options .

QDialogButtonBox( Standard button box ) Provide a series of standard buttons , It can be arranged horizontally or vertically , Commonly used in dialog boxes and message boxes . Qt The standard buttons defined include :Yes、No、OK、Cancel、Ignore、Open、Save、Close、Apply、Help wait , Users can customize and add .



3. Input control

3.1 Enter an introduction to the control

stay QtDesigner Left side “WidgetBox” In the toolbar "Input Widget" Group , There are many different types of input controls , for example :
Text input control :QlineEdit( Single line input )、QTextEdit( Multi line input )、QPlainTextEdit( Common multiline input );
Digital input control :QSpinBox( Integer data input )、QDoubleSpinBox( Floating point data input );
Adjust the input control :QAbstractSpinBox( Step adjustment input )、QDateEdit( Date input )、QTimeEdit( Time input )、QDateTimeEdit( Date and time input ).

Drag the input control in the toolbar to QtDesigner The middle graphical interface editing window , Just create a button control in the image interface . As shown in the previous figure , We are in the graphical interface uiDemo5.ui Middle and right of , Created several different input controls .


3.2 Text input control

Single line text input box (QlineEdit)

QLineEdit Control is a single line text editor , Allows the user to enter and edit single line text , And supports undo 、 redo 、 shear 、 Paste and drag and drop functions .

QLineEdit Properties of control 、 The signal 、 There are many functions , And support password input mode 、 The text box is automatically completed , I will not give a detailed introduction at this time , Interested readers can view relevant documents and routines .

Multiline text input box (QTextEdit)

QTextEdit Control is a “ What you see is what you get ” Multi line rich text editor , Allows users to enter and edit multiline text , And support HTML4 Label subsets , Can load plain text and rich text files , Suitable for editing and browsing large rich text files .

QTextEdit For paragraphs and characters . Can display images , Lists and tables . If the text is too large to view in the viewport where the text is edited , A scroll bar appears .

TextEdit You can not only display text , You can also show HTML file

Common multiline input (QPlainTextEdit)

QPlainTextEdit Control is a multi line plain text editor , Allows users to enter and edit multiple lines of plain text , Tables or embedded frames are not supported . The processing of plain text is optimized , Can handle larger documents and faster responses .


3.3 Adjust the input control

Step adjustment input (QAbstractSpinBox)

QAbstractSpinBox The common functions of all step regulators are abstracted into a parent class , You can also directly instantiate .QAbstractSpinBox Contains a QLineEdit And two QPushbutton, The data can be changed by clicking the button or using the keyboard .

Date and time input (QDateEdit/QTimeEdit/QDateTimeEdit)

QDateEdit Control is used to edit the date ,QTimeEdit Control is used to edit the time ,QDateTimeEdit Edit the date and time control at the same time . You can use the up and down buttons on the keyboard to increase or decrease the date 、 Time .

Integer digital adjustment frame (QSpinBox)

QSpinBox Is a counter control , Allows the user to select an integer and press the up and down buttons to increment or decrement , You can also directly enter the value of an integer . The default value range is 0-99, The step size of each adjustment is 1.

Floating point number adjustment box (QDoubleSpinBox)

QDoubleSpinBox Is a floating-point data counter control , Used to process floating-point values . The default precision is 2 Decimal place .-



4. Python The application invokes the graphical interface

stay QtDesigner Save the graphical interface of the design as uiDemo5.ui, function PyUIC Will be selected .ui The file is converted to .py file , Generate... In this path uiDemo5.py file .

We write a graphical interface for the main program call design uiDemo5.py, You can complete a graphical interface application .

# GUIdemo5.py
# Demo5 of GUI by PyQt5
# Copyright 2021 youcans, XUPT
# Crated:2021-10-12
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from uiDemo5 import Ui_MainWindow # Import uiDemo5.py Medium Ui_MainWindow Interface class 
class MyMainWindow(QMainWindow, Ui_MainWindow): # Inherit QMainWindow Classes and Ui_MainWindow Interface class 
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent) # Initializes the parent class 
self.setupUi(self) # Inherit Ui_MainWindow Interface class 
def trigger_actHelp(self): # action actHelp Trigger 
QMessageBox.about(self, "About",
""" Digital image processing toolbox v1.0\nCopyright YouCans, XUPT 2021""")
return
if __name__ == '__main__':
app = QApplication(sys.argv) # stay QApplication Method used in , Create application objects 
myWin = MyMainWindow() # Instantiation MyMainWindow class , Create main window 
myWin.show() # Display controls on the desktop myWin
sys.exit(app.exec_()) # The end of the process , Exit procedure 

Because this article mainly introduces the common basic controls , The signal of the control has not been connected to the slot function in the program , So run the program uiDemo5.py when , Some of these button controls do not trigger actions after clicking .

In the next article , We will introduce PyQt5 Page layout in .

【 At the end of this section 】


Copyright notice :

Welcome to your attention 『Python Xiaobai starts from scratch PyQt5 Project practice @ Youcans』 Original works

Original works , Reprint must be marked with the original link :(https://blog.csdn.net/youcans/article/details/120665014)

Copyright 2021 youcans, XUPT

Crated:2021-10-12


Welcome to your attention 『Python Xiaobai starts from scratch PyQt5 Project practice @ Youcans』 series , Ongoing update
Python Xiaobai starts from scratch PyQt5 Project practice (1) Installation and environment configuration
Python Xiaobai starts from scratch PyQt5 Project practice (2) Menus and toolbars
Python Xiaobai starts from scratch PyQt5 Project practice (3) Signal to slot connection
Python Xiaobai starts from scratch PyQt5 Project practice (4) Basic controls

版权声明
本文为[youcans]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013141230663e.html

  1. 预备知识-python核心用法常用数据分析库(下)
  2. python 文件排版,怎么控制写入在对应文件的位置(要写吐了,真是服了)
  3. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅰ)
  4. Typographie de fichiers Python, comment contrôler l'écriture à l'emplacement du fichier correspondant (pour écrire et vomir, vraiment pris)
  5. python:例题求解,不知道怎么等输入完所有数字后再输出
  6. 用python来实现:根据实际查询结果补充完整数据
  7. Mise en œuvre en python: compléter les données complètes en fonction des résultats réels de la requête
  8. python对excel进行分组但不进行聚合统计操作,且输出到不同的表格中?
  9. Python regroupe Excel, mais n'effectue pas de statistiques agrégées, et l'affiche dans différents tableaux.
  10. python如何提交,不要用太复杂的函数
  11. Comment soumettre Python sans utiliser de fonctions trop complexes
  12. Python,数据文件操作问题,想要代码
  13. python 提取多个字符串中的多个字段
  14. python 读入用户输入的一组正整数,到-1结束
  15. Python lit un ensemble d'entiers positifs entrés par l'utilisateur, se terminant par - 1
  16. 测试逐飞的MM32F3277 MicroPython开发板的基本功能
  17. Python timer reference
  18. 关于#python#的问题:python3队列维护
  19. Developing Hongmeng equipment program using python (3-prototype of security system)
  20. Questions sur # # Python #: maintenance de la file d'attente Python 3
  21. 怎么用Python打印数字三角
  22. 怎麼用Python打印數字三角
  23. Comment imprimer un triangle numérique en python
  24. Tester la fonctionnalité de base du tableau de développement microspython mm32f3277 Flying - by - flying
  25. Python extrait plusieurs champs de plusieurs chaînes
  26. Pandas核心用法
  27. Utilisation centrale de pandas
  28. Python, problème de fonctionnement du fichier de données, Code désiré
  29. 【78技术人社群~Python分部】,就在今天成立 →
  30. 社区共读《Python编程从入门到实践》第一天阅读建议
  31. La communauté lit les recommandations de lecture pour la première journée de la programmation Python de l'introduction à la pratique
  32. [78 Communauté des technologues ~ Division Python], fondée aujourd'hui →
  33. Pandas核心用法
  34. 您好,请问您的python按钮开了线程处理还卡ui的问题解决了吗
  35. Python: résolution d'exemples, je ne sais pas comment attendre que tous les chiffres soient entrés avant de sortir
  36. Bonjour, puis - je vous demander si votre bouton Python est activé pour le traitement du thread et le retour de l'interface utilisateur de la carte a été résolu?
  37. Utilisation centrale de pandas
  38. Python technique 2: advanced usage of function parameters
  39. OpenCV-Python实战(14)——人脸检测详解(仅需6行代码学会4种人脸检测方法)
  40. OpenCV-Python實戰(14)——人臉檢測詳解(僅需6行代碼學會4種人臉檢測方法)
  41. OpenCV - Python Real play (14) - face detection details (six lignes de code seulement pour apprendre 4 méthodes de détection de visage)
  42. 你好,python开发mes系统,能分享下吗,我最近也想搞这方面的
  43. 你好,python開發mes系統,能分享下嗎,我最近也想搞這方面的
  44. Bonjour, Python a développé mon système, pouvez - vous le partager?
  45. Introduction to tuples in Python
  46. Introduction to strings in python (Part 2)
  47. Introduction to strings in python (Part 1)
  48. python关于 if 的简单操作时,输出结果不是预期所要的结果 的问题
  49. python關於 if 的簡單操作時,輸出結果不是預期所要的結果 的問題
  50. Lorsque Python fonctionne simplement sur if, la sortie n'est pas le résultat attendu
  51. Python中字典问题请求解惑
  52. Python中字典問題請求解惑
  53. Demande de résolution de problèmes de dictionnaire en python
  54. Python中字典问题请求解惑
  55. Python technique 2: advanced usage of function parameters
  56. Demande de résolution de problèmes de dictionnaire en python
  57. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅱ)
  58. 关于python的代码问题,终端打印为什么会起飞
  59. En ce qui concerne les problèmes de code Python, pourquoi l'impression du terminal décolle - t - elle?
  60. Python中种子seed的运用问题