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 .
This paper explains the connection mechanism between signal and slot , Demonstrate various types of signals in detail / Implementation method of slot connection , This is the core of the graphical user interface .
This paper will also introduce object-oriented programming , This is the basic idea of graphical user interface .
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
The signal and slot mechanism is PyQt The core mechanism of , Used for communication between objects , That is to realize the automatic call between functions .
In short , Connect the signal to the slot function , When the signal is triggered , The slot function will be called automatically .
Analyze the process , It involves several basic concepts and relationships :
The sender of the signal is usually a control object , Send a signal when the state of the control object changes . Common senders are various control objects in the graphics window , But it can also be an action object .
The receiver of the slot is usually also a control object . Slot function is a custom slot function , Or the built-in slot function of the control . In a general way , The slot function also has an object as the body , That is, perform the operation defined by the function for the recipient control object . For example, the function performed by the slot function is to close , So what exactly is to close that control ? The closing object is the recipient .
In order to explain the connection between signal and slot , We use it QtDesigner The graphic window designed in the previous section uiDemo3.ui On the basis of , Add several button objects and text line editing objects :
open PyCharm, from Tools -> ExternalTools -> QtDesigner open QtDesigner, open uiDemo3.ui file .
Click to select QtDesigner Left control bar Buttons Medium PushButton, Hold the mouse down , Drag it to the middle graphical interface and release the mouse , Just create a... In the graphical interface PushButton Control .
Click to select QtDesigner Left control bar InputWidget Medium LineEdit, Hold the mouse down , Drag it to the middle graphical interface and release the mouse , Just create a... In the graphical interface LineEdit Control .
Repeat the above steps , Build a few more PushButton Controls and LineEdit Control .
Select the created in the graphical interface with the mouse PushButton Control or LineEdit Control , You can drag the control to adjust the position .
Mouse click PushButton Button , You can edit the label of the button control, that is, the display content on the button .
For ease of explanation , This example will each PushButton The display content of the control (text attribute ) It is amended as follows :“1# Button ” ~ “4# Button ”, Will each LineEdit The display content of the control (text attribute ) It is amended as follows :“ Text edit line -1” ~ “ Text edit line -3”.
Save the application graphical interface as uiDemo4.ui, The preview effect is as follows :
QtDesigner Provides convenient and intuitive signals / Slot editing method .
This example introduces different senders and receivers , Slot function is the operation method of the built-in function of the control . Several methods are built into different types of controls , for example QPushButton Control's built-in methods include : Click on 、 Choose 、 State change 、 Display menu, etc , and QLineEdit Control's built-in methods include : Empty 、 Copy 、 shear 、 Paste 、 Future generations 、 Undo operation, etc . Use the built-in method of the control as the slot function , Can be called directly , There is no need to define functions .
The function we designed is : When you click the button control “pushButton_1” when , Empty the text editing control “lineEdit_1” Display content of . Note that we call the button control “lineEdit_1” instead of “ Text edit line -1”, This is because lineEdit_1 Is the name of the control , It is constant in the program , and “ Text edit line -1” Just show the content , Can be modified in the program .
QtDesigner Set signal / The operation steps of slot connection are as follows :
This example introduces different senders and receivers , Slot function is the operation method of user-defined function .
stay 2.1 The use of the built-in method of the control as the slot function is introduced in , Can be called directly , There is no need to define functions . The core function in programming is usually the user-defined function developed by the programmer according to the requirements . Use custom functions as slot functions , On the one hand, of course, it is necessary to write custom functions , On the other hand, add the custom function to the slot function configuration connection table .
The function we designed is : When you click the button control “pushButton_2” when , Empty the text editing control “lineEdit_2” Display content of , And display text information “current signal: click pushButton_2”. In the main program, a user-defined function should be written to realize this function , Name the custom function click_pushButton_2().
Notice the custom function we wrote click_pushButton_2(), Although the function is only for text editing controls “lineEdit_2” To operate , But for custom functions, you can also complete any other functions , Operate on other controls according to the control name . Therefore, the receiver of the slot function is not a text editing control “lineEdit_2”, It's the main window control “MainWindow”.
QtDesigner Set signal / The operation steps of slot connection are as follows :
** In the first QtDesigner Add a custom function to the slot function configuration connection table —— It's very important .** Many articles on the Internet do not talk about the specific implementation method , The entrance to this operation is also difficult to find .
Then set the signal / Slot connection :
Last , Don't forget to write custom functions in the main program . But this does not belong to QtDesigner The content of the design , I will not go into details here .
Similarly , We design : When you click the button control “pushButton_3” when , In the text editing control "lineEdit_1" Displays the current system date , In the text editing control "lineEdit_2" Display the current system time , In the text editing control “lineEdit_3” Display prompt message . Write a custom function in the main program click_pushButton_3(), And with “pushButton_3” Set up the signal / Slot connection .
This shows that : In a custom subfunction , You can manipulate multiple control objects at the same time , Then, various user-defined functions can be realized .
This example introduces the same sender and receiver , Slot function is the operation method of the built-in function of the control .
seeing the name of a thing one thinks of its function , The same sender and receiver , That is, the sender of the signal and the receiver of the slot function are the same control object . What's going on here ? for example , A switch button has “On/Off” Two kinds of state , Each time you press the button, the button status will flip . Similarly , The option box is also checked 、 There are no two states selected . Specifically , After clicking the button , Close the button control , Also belong to the same sender and receiver .
Let's start with the control object “pushButton_4” From the button control QPushButton Change for Option box control “QCheckBox”:
here , Design the button control in the interface window , It becomes an option box . meanwhile , On the right side “ Object viewer ” Control in “pushButton_4”, Also automatically changed to “checkBox_4”. Changed controls “checkBox_4” Inherited the original control “pushButton_4” Some properties of , Such as : Location 、 Size 、 According to the content .
Next, set the signal / Slot connection :
Common signal senders are various control objects in the graphics window , But it can also be an action object . This example describes how to establish the connection between signal and slot for control objects in menu bar and toolbar .
When the sender of the signal is the action object , The receiver of the signal is usually the top-level object “MainWindow”, The slot function can be an object “MainWindow” Built in functions for , It can also be a custom function .
In the last article, we worked on actions in the menu bar and toolbar “actionQuit” Set up the signal / Slot connection , The sender is the action object 、 Connect to object “MainWindow” A case of built-in functions . The operation process is as follows :
The purpose of the above operation is : sender object “actionQuit” Trigger “triggered()” when , The receiver object "MainWindow" Execute slot function “closed()”.
Now let's do another action “actionHelp” Set up the signal / Slot connection , The connected slot function is a user-defined function trigger_actHelp(). The operation process is as follows :
thus , This chapter introduces the use of QtDesigner Carry out several common signals / Editing and setting method of slot connection . As shown in the figure below , stay QtDesigner The signal added in / Slot connections will be in the signal / The slot editor window displays .
In the last section QtDesigner The design of graphical interface is completed , Save the file as uiDemo4.ui. open PyCharm, Select Chinese file uiDemo4.ui, Use PyUIC It can be converted to uiDemo4.py.
Next, we will write the main program of graphical interface , Call the graphical interface design file uiDemo4.py.
Process oriented programming
In the last article , After we create the main window in the main program , Call directly UI Medium Ui_MainWindow(). This is a process oriented programming method .
# GUIdemo3.py
import uiDemo3 # Import image interface design file
if __name__ == '__main__':
app = QApplication(sys.argv) # Create application objects
MainWindow = QMainWindow() # Create main window
ui = uiDemo3.Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show() # Show the main window
sys.exit(app.exec_()) # Exit in the main thread
Object oriented programming
With the deepening of the project , We need to deal with richer graphical interfaces and realize more complex software functions , The scale of the program is growing , The structure of the program is becoming more and more complex .
Object oriented programming makes the structure of the program clearer , So it's easy to read 、 understand 、 Development and maintenance , Very suitable for large-scale development 、 Multitasking graphical interface application software .PyQt5 Class in 、 object 、 Controls and methods , Are the concepts of object-oriented programming . therefore , From the beginning of this paper, we adopt the object-oriented programming method , To write the main program of graphical interface .
routine GUIdemo4.py as follows :
from uiDemo4 import Ui_MainWindow # Import uiDemo4.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
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
In the above routine , We created a class MyMainWindow(), It inherited QtWidgets.QMainWindow Class methods and imported uiDemo4.py Medium Ui_MainWindow Interface class .
“super(MyMainWindow, self).init()”: Initializes the parent class , hold MyMainWindow The object of self Convert to parent class QMainWindow object , And call init function .
“self.setupUi(self)”: Inherit uiDemo4.py Medium Ui_MainWindow Interface class , call Ui_MainWindow Class setupUi() Method .
Little white who is not familiar with object-oriented programming , It doesn't matter if you don't understand this program , Just save it and draw a picture .
Run routines GUIdemo4.py. Why , Wrong report :
AttributeError: ‘MyMainWindow’ object has no attribute ‘click_pushButton_2’
The system prompts that... Cannot be found ‘click_pushButton_2’, This is because... Has not been written in the main program 2.2 Custom slot function in .
The custom slot function click_pushButton_2()、click_pushButton_3、trigger_actHelp(self) Add to the main program . The following is a routine GUIdemo4.py Complete code .
# GUIdemo4.py
# Demo4 of GUI by PyQt5
# Copyright 2021 youcans, XUPT
# Crated:2021-10-10
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from uiDemo4 import Ui_MainWindow # Import uiDemo4.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 click_pushButton_2(self): # Click on pushButton_2 Trigger
self.lineEdit_2.setText("click_pushButton_2")
return
def click_pushButton_3(self): # Click on pushButton_3 Trigger
from datetime import datetime # Import datetime library
nowDate = datetime.now().strftime("%Y-%m-%d") # Get current date "2021-10-10"
nowTime = datetime.now().strftime("%H:%M:%S") # Get the current time "16:58:00"
self.lineEdit_1.setText("Current date: {}".format(nowDate)) # Show date
self.lineEdit_2.setText("Current time: {}".format(nowTime)) # Display time
self.lineEdit_3.setText("Demo4 of GUI by PyQt5") #
return
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
Now we have a simple but complete object-oriented graphical interface application GUIdemo4.
Check the application GUIdemo4 All the functions of :
If all the above tests are successful , So congratulations to Xiaobai , You have mastered the use of QtDesigner Design PyQt5 Basic functions of graphical interface .
In the next article , We will introduce PyQt5 Common controls 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/120664900)
Copyright 2021 youcans, XUPT
Crated:2021-10-10
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