SoFunction
Updated on 2024-11-20

Python deep learning combat PyQt5 basic control use analysis

1. PyQt5 control introduction

1.1 What are controls

Controls, also known as control objects, are the most basic type of component in the Qt user interface and form the basic structure of the user interface. Everything displayed on the user interface is a control, such as buttons, labels, text boxes, menu bars, toolbars, status bars, and even the entire window itself.

The QWidget class is the base class of PyQt5 and the parent class of all controls. All Qt controls are subclasses of the QWidget class and therefore inherit the features of the QWidget class to receive user input events, such as mouse and keyboard input, and to display the contents of the control in the user interface and to store other controls.

1.2 Editing the properties of a control

Controls have properties. Different types of controls have some of the same properties and some different proprietary properties.

The same properties of a control include: name, shape, position, size, set format. Specialized properties of a control include: display content, accept input, user interaction, date, frame, and more.

All Qt controls are subclasses of the QWidget class and inherit properties from the QWidget class. Therefore, we can learn controls by class, first learning the common properties of the inherited parent class, and then learning the proprietary properties that are specific to the control. Learning about controls is a structural diagram of class inheritance relationships.

Let's take the graphical interface as an example to introduce the general properties of the control and to edit the properties of the control.

As already mentioned, the "Object Viewer" on the upper right side of QtDesigner shows the names and structures of the controls in the interface, and the "Property Editor" at the bottom shows the properties of the selected control object. Selecting a control in the graphical interface or selecting a control in the Object Viewer displays the properties of the control object in the Property Editor.

在这里插入图片描述

Whether it's the window object MainWindow, the menu bar menubar, the toolbar toolBar, or the button pushButton, or the edit line lineEdit, they all have some of the same properties, for example:

objectNameThe control name is very important. It is the ID of the control, the objectName is used in Python programs to access the control and interact with it, all controls must have a unique objectName, no renaming. No Chinese characters can be used.

geometry: The size and position of the control.

  • The width and height of the control can be modified. The width/height of the control is the width/height of the GUI program window for MainWindow.
  • The control position (X, Y) is the coordinate value of the control in the window control. The control position of the MainWindow cannot be modified, while the position (X, Y) of the other controls can be modified as needed.
  • minimumSize, maximumSize are the minimum and maximum size of the control object after the main window size is stretched.

font: The font selection displayed by the control, including options for font, font size, style, and effects.

1.3 Types of controls in PyQt5

To learn about the subclasses of the QtWidgets class, you can use "subclasses()" to print out all the subclasses, of which there are about 30.

    import PyQt5
    print(.__subclasses__())

These control types, in general, can be categorized as follows:

Input Controls:

  • Buttons: QPushButton (key button), QToolButton (tool button), QRadioButton (radio box), QCheckButton (multi-select box), QCommandLinkButton (button for connecting commands)
  • Keyboard input controls: QlineEdit (single line input), QTextEdit (multi-line input), QPlainTextEdit (normal multi-line input), QkeySequenceEdit (shortcut key input)
  • Adjustment input controls: QAbstractSpinBox (step adjustment input), QDateEdit (date input), QTimeEdit (time input), QDateTimeEdit (date and time input)
  • Numeric SpinBox controls: QSpinBox (Integer SpinBox), QDoubleSpinBox (Floating Point SpinBox).
  • Slider input controls: QDial (rotary drag and slide input), QSlider (linear drag input), QScrollBar (scroll bar), QRubberBand (rubber band drag)
  • Drop-down input controls: QComboBox (combo box drop-down option), QSlider (straight line drag input), QScrollBar (scroll bar), QRubberBand (rubber band drag)
  • Dialog input controls: QDialog (dialog box), QColorDialog (color dialog box), QFileDialog (file dialog box), QFontDialog (font dialog box), QInputDialog (input dialog box)
  • Calendar control: QCalendarWidget (date selection widget)

Display Controls:

  • Content display controls: QLabel (display box), QLCDNumber (LCD), QProgressBar (progress bar)
  • Dialog display controls: QMessageBox (message box), QErrorMessage (error message box), QProgressDialog (progress message box)

Advanced Controls:

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

In the "WidgetBox" toolbar on the left side of QtDesigner, frequently used controls are grouped by category. Drag and drop the control icon from the toolbar with the mouse to the GUI editing window in the middle of QtDesigner to create a control of your choice in the image interface.

在这里插入图片描述

2. Button controls

2.1 Introduction to Button Controls

Buttons are the most commonly used type of control.

In the "Buttons" group of the "WidgetBox" toolbar on the left side of QtDesigner, there are several different types of button controls: PushButton, QToolButton, QRadioButton, QCheckButton, QCommandLinkButton, QDialogButtonBox (standard button box) provides a series of standard buttons that are equivalent to command buttons. QDialogButtonBox provides a series of standard buttons, which are equivalent to combinations of button controls.

Common properties of button controls:

text: Display Text

icon: Setting Icons

iconSize: Icon size

shortcut: Setting Shortcuts

checkable: Set whether to switch buttons automatically

checked: Setting the Default Selected State

autoRepeat: Whether the setting is repeated automatically when the user presses the

autoExclusive: Set whether to enable automatic exclusivity (set multiple checkboxes)

Signal trigger conditions for the button control:

clicked(): signals when the button is first pressed and then released

clicked(bool): Signal when a button is first pressed and then released, and communicate the current state to the outside world

pressed(): Press the left mouse button to signal when the mouse cursor is inside a button

released(): Signal when the left mouse button is released

toggled(bool): Signal a change in the state of the button and communicate the current state to the outside world.

The common modes/states of the button control:

  • Available or not available, button grayed out when disabled
  • Standard buttons, switch buttons or menu buttons
  • Open or close (for switch buttons only)
  • Default or normal state
  • Whether to repeat automatically
  • Whether it is pressed or not

A button control is created in the image interface by dragging and dropping the button control from the toolbar with the mouse to the GUI editing window in the middle of QtDesigner. As you can see in the following figure, we have created several different button controls on the left side of the GUI.

在这里插入图片描述

2.2 Push button (QPushButton)

QPushButton (Key Button) is the most commonly used button. Pressing (or clicking) the button performs an action or answers a question, e.g. OK, Apply, Cancel, Close, Yes, No and Help.

The button control usually displays a text label, and you can choose an icon for the button, and optionally set a shortcut.

The above properties of a button can be edited and modified in the corresponding property line of the Property Editor.

When a pushbutton is activated by a mouse or shortcut, the button emits the clicked() signal, which can be used to trigger a specific action by connecting to a slot function.

2.3 Other buttons

QToolButton(Tool buttons are often used in toolbars and are usually created when a QAction instance is created. Tool buttons usually display an icon that provides quick access to a specific command or option.

QRadioButton(RadioBox) is a radio box with a text label that can be turned on (checked) or off (unchecked). The "toggled()" signal is emitted when the radio box is checked or cleared, and can be used to trigger specific actions by connecting to slot functions.

QCheckButton(MultiCheckBox) is a checkbox with a text label that provides a half-selected state (optional) in addition to being turned on (checked) or off (unchecked). Checkboxes emit a "stateChanged()" signal when they are checked or cleared, which can be used to trigger specific actions by connecting to slot functions.

A radio box defines a "multiple choice" selection, while a checkbox provides a "multiple choice" selection.

QCommandLinkButton(the button that connects commands) looks like a flattened QPushButton and comes with a rightward-facing icon, which is used in a similar way to a radio button that is used to select between a set of mutually exclusive options.

QDialogButtonBox(Standard Button Box) provides a series of standard buttons that can be arranged horizontally or vertically and are commonly used in dialog boxes and message boxes. The standard buttons defined by Qt include: Yes, No, OK, Cancel, Ignore, Open, Save, Close, Apply, Help, etc., which can be customized by the user.

3. Input controls

3.1 Introduction to Input Controls

The "Input Widget" group in the "WidgetBox" toolbar on the left side of QtDesigner has several different types of input controls, for example:
Text input controls: QlineEdit (single line input), QTextEdit (multi-line input), QPlainTextEdit (normal multi-line input);
Numeric input controls: QSpinBox (integer data input), QDoubleSpinBox (floating point data input);
Adjustment input controls: QAbstractSpinBox (step adjustment input), QDateEdit (date input), QTimeEdit (time input), QDateTimeEdit (date and time input).

By dragging and dropping the input control from the toolbar with the mouse onto the GUI editing window in the middle of QtDesigner, a button control is created in the image interface. As you can see in the previous figure, we have created several different input controls in the center and on the right side of the GUI.

3.2 Text Input Controls

Single line text input box (QlineEdit)

The QLineEdit control is a single line text editor that allows you to enter and edit single lines of text and supports Undo, Redo, Cut, Paste and Drag & Drop functionality.

QLineEdit control has more attributes, signals, functions, and support for password input methods, text box auto-completion, this is not a detailed introduction, interested readers can view the relevant documents and routines.

Multi-line text input box (QTextEdit)

The QTextEdit control is a "WYSIWYG" multi-line rich text editor that allows users to enter and edit multi-line text with support for a subset of HTML4 tags, and loads both plain and rich text files, making it ideal for editing and browsing large rich text files.

QTextEdit works with paragraphs and characters. Images, lists and tables can be displayed. If the text is too large to be viewed in the text editor's viewport, a scroll bar will appear.

TextEdit can display not only text, but also HTML documents.

Normal multi-line input (QPlainTextEdit)

The QPlainTextEdit control is a multi-line plain text editor that allows users to enter and edit multiple lines of plain text, without supporting tables or embedded frames. Optimized for plain text handling, it can handle larger documents and respond faster.

3.3 Adjusting Input Controls

Step Adjustment Input (QAbstractSpinBox)

QAbstractSpinBox abstracts the functionality common to all step adjusters into a parent class, which can also be instantiated directly.QAbstractSpinBox contains a QLineEdit and two QPushbuttons, where changes to the data can be made by clicking on the buttons or by using the keyboard.

Date and time input (QDateEdit/QTimeEdit/QDateTimeEdit)

QDateEdit control for editing date, QTimeEdit control for editing time, QDateTimeEdit control for editing both date and time. You can use the up and down header buttons on the keyboard to increase or decrease the date and time.

Integer numeric adjustment box (QSpinBox)

QSpinBox is a counter control that allows you to select an integer to be incremented or decremented by pressing the up and down buttons, or you can enter the value of the integer directly. The default value range is 0-99 and the step size is 1.

Floating Point Number Adjustment Box (QDoubleSpinBox)

QDoubleSpinBox is a floating point data counter control for working with floating point values. The default precision is 2 decimal places. -QDoubleSpinBox

4. Python applications invoke the GUI.

Save the designed GUI in QtDesigner as , run PyUIC to convert the selected .ui file to a .py file and generate the file in that path.

We write a main program to call the designed graphical interface , you can complete a graphical interface application.

# 
# Demo5 of GUI by PyQt5
# Copyright 2021 youcans, XUPT
# Crated:2021-10-12
import sys
from  import QApplication, QMainWindow, QMessageBox
from uiDemo5 import Ui_MainWindow  # Ui_MainWindow interface class in the import
class MyMainWindow(QMainWindow, Ui_MainWindow):  # Inherit the QMainWindow class and the Ui_MainWindow interface class.
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)  # Initialize the parent class
        (self)  # Inherit Ui_MainWindow interface class
    def trigger_actHelp(self):  # action actHelp trigger
        (self, "About",
                          """Digital Image Processing Toolbox v1.0\nCopyright YouCans, XUPT 2021""")
        return
if __name__ == '__main__':
    app = QApplication()  # Used in the QApplication method to create an application object
    myWin = MyMainWindow()  # Instantiate the MyMainWindow class to create the main window
    ()  # Display the control myWin on the desktop
    (app.exec_())  # End the process and exit the program

Since this article mainly introduces the common basic controls, the signal connection slot function of the control has not yet been included in the program, so when the program is run, some of the buttons do not trigger an action when they are clicked.

In the next article, we'll cover page layout in PyQt5.

portalPython Deep Learning Practical PyQt5 Layout Management Project Sample Details

Above is the detailed content of Python deep learning combat PyQt5 basic control use analysis, more information about the use of PyQt5 basic control please pay attention to my other related articles!