Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to connect PyQt5 signal and slot in Python

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to connect PyQt5 signals and slots in Python. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. Signal and slot (Signals and slots)

Signal and slot mechanism is the core mechanism of PyQt, which is used for the communication between objects, that is, to realize the automatic call between functions.

1.1 the principle of signals and slots

To put it simply, after the signal is connected to the slot function, when the signal is triggered, the slot function will be called automatically.

The analysis of this process involves several basic concepts and relationships:

Signal: the signal can be an action or a state of the object that triggers the connected slot.

Slot: a slot is a function that can be triggered by a connected signal.

Transmit signal: when the signal is transmitted, the slot function of the signal connection is automatically called. Usually, a signal is transmitted when the state of the object changes.

The signal can have parameters, but it must correspond to the parameters of the slot function.

A signal can be connected to multiple slot functions, and multiple signals can also be connected to a slot function.

One signal can be connected to another.

Many widgets (controls) have built-in signals and slots that can be called directly. You can also customize signals and slots as needed.

1.2 signal sender and slot receiver

The sender of a signal is usually a control object that sends a signal when the state of the control object changes. A common sender is a variety of control objects in the graphics window, but they can also be action objects.

The receiver of the slot is usually also a control object. The slot function is a custom slot function, or a slot function built into the control. In general, the slot function also has an object as the body, that is, to perform a function-defined operation on the recipient control object. For example, the function performed by the slot function is to close, so which control is closed? The closed object is the recipient.

In order to explain the connection between signal and slot, we use QtDesigner to add several button objects and text line editing objects to the graphic window uiDemo3.ui designed in the previous section.

Open PyCharm, open QtDesigner from Tools-> ExternalTools-> QtDesigner, and open the uiDemo3.ui file.

Click the mouse to select the PushButton in the Buttons control bar on the left side of the QtDesigner, hold down the mouse, drag it to the middle graphical interface, release the mouse, and create a PushButton control in the graphical interface.

Click the mouse to select the LineEdit in the InputWidget control bar on the left side of the QtDesigner, hold down the mouse, drag it to the middle graphical interface, release the mouse, and create a LineEdit control in the graphical interface.

Repeat the above steps to create several more PushButton and LineEdit controls.

Notice the control names and properties displayed in the object Viewer on the right side of QtDesigner, multiple PushButton and LineEdit are automatically given different names (objectName), such as LineEdit_1, LineEdit_2, LineEdit_3, just as several drawers of the table are marked as "drawer 1", "drawer 2", "drawer 3" for identification.

The name of the control and other properties can be edited and modified in the property Editor.

By selecting the PushButton control or LineEdit control created in the graphical interface, you can drag the control to adjust its position.

By double-clicking the PushButton button, you can edit the label of the button control, that is, the display on the button.

In order to facilitate explanation, this example changes the display content of each PushButton control (text property) to: "button" ~ "button", and the display content of each LineEdit control (text property) to: "text edit line-1" ~ "text edit line-3".

Save the application graphical interface as uiDemo4.ui, and the preview effect is as follows:

2. QtDesigner establishes the connection between signal and slot 2.1The connection between signal and slot: different senders and receivers, slot function is the built-in function of the control.

QtDesigner provides a convenient and intuitive method for signal / slot editing.

This example introduces the operation of different senders and receivers, and the slot function is the built-in function of the control. Different types of controls have several built-in methods, for example, the built-in methods of QPushButton control include: click, select, state change, display menu, etc., while the built-in methods of QLineEdit control include: empty, copy, cut, paste, select all, undo operation and so on. Use the built-in method of the control as a slot function, which can be called directly without the need to define the function.

The function we designed is to clear the display of the text editing control "lineEdit_1" when the button control "pushButton_1" is clicked. Note that we call the button control "lineEdit_1" instead of "text edit line-1". This is because lineEdit_1 is the control name, which is unchanged in the program, while "text edit line-1" only displays the content and can be modified in the program.

The steps for QtDesigner to set up the connection of signals / slots are as follows:

(1) Select the menu item "Edit"-> Edit signal / slot, or enter signal / slot editing mode through the shortcut key F4 or select in the toolbar.

(2) Select the sender of the control object. Here is the button control "pushButton_1". If the left mouse button is pressed and held down, the button control turns light red.

The left mouse button continues to press and move the mouse, and when the mouse moves out of the control object area, a red line with an arrow and a red grounding symbol appear.

The left mouse button continues to be pressed for a long time, and drag the mouse to the control object "lineEdit_1", release the left mouse button, and establish a signal / slot connection with the control object "pushButton_1" as the sender and the control object "lineEdit_1" as the receiver.

At this point, the control objects "pushButton_1" and "lineEdit_1" turn light red, and the red lines with arrows start from "pushButton_1" and point to "lineEdit_1".

(3) the dialog box "configure connection-QtDesigner" pops up at the same time, the left side of the dialog box shows the signal options of the sender control, and the right side of the dialog box shows the control options of the receiver.

According to the functional requirements, the trigger signal is that the button "pushButton_1" is clicked, and select "clicked ()" from the left side of the dialog box.

According to the functional requirements, the action after receiving the signal is to empty the text editing control "lineEdit_1" and select "clear ()" from the right side of the dialog box.

Click the button "OK" at the bottom of the dialog box to complete the configuration of the signal / slot connection.

2.2 connection between signal and slot: different senders and receivers, slot function is a custom function

This example introduces the operation of different senders and receivers, and the slot function is a custom function.

In 2.1, it is introduced to use the built-in method of the control as a slot function, which can be called directly without the need to define the function. The core function in programming is usually the custom function developed by the programmer according to the requirements. Using the custom function as the slot function, on the one hand, of course, we should write the custom function, on the other hand, we should add the custom function to the slot function configuration connection table.

The functions we designed are:

When the button control "pushButton_2" is clicked, the display of the text editing control "lineEdit_2" is cleared and the text message "current signal: click pushButton_2" is displayed.

In the main program, a custom function is written to implement this function, and the custom function is named click_pushButton_2 ().

Note that we write the custom function click_pushButton_2 (), although the function is only for the text editing control "lineEdit_2" to operate, but for the custom function can also complete any other functions, other controls according to the control name operation. So the receiver of this slot function is not the text editing control "lineEdit_2", but the main window control "MainWindow".

The steps for QtDesigner to set up the connection of signals / slots are as follows:

It is important to first add the custom function to the slot function configuration connection table in QtDesigner.

Many articles on the Internet do not talk about the specific implementation methods, and the entrance to this operation is also very difficult to find.

(1) in the "object Viewer" above the right side of QtDesigner, select MainWindow or other top-level objects, right-click to call out the drop-down menu, and select "change signal / slot".

Pop-up "signal / slot of MainWindow" dialog box, the top of the dialog box shows the options of the slot, and below shows the signal options.

Click the green "+" at the bottom of the "slot" option box at the top of the dialog box, and the system automatically adds a line "slot1 ()" at the end of the "slot" option table. This is the new custom slot function.

Click to select "slot1 ()", and then double-click the mouse to change the function name of the slot function, for example, to click_pushButton_2 ().

Then click the green "+" at the bottom of the "slot" option box at the top of the dialog box, and you can continue to add custom slot functions one by one.

Then set the connection of the signal / slot:

(2) Select the menu item "Edit"-> Edit signal / slot, or enter signal / slot editing mode through the shortcut key F4 or select in the toolbar.

Select the sender of the control object, here is the button control "pushButton_2", press the left mouse button and move, when the mouse moves out of the control object area, a red line with an arrow and a red grounding symbol appear.

Release the left mouse button to establish a signal / slot connection with the control object "pushButton_2" as the sender and the control object "MainWindow" as the receiver. At this point, the control object "pushButton_2" turns light red, and the red line with arrows starts from "pushButton_2" and does not point to other controls, but ends with a grounding symbol.

(3) the dialog box "configure connection-QtDesigner" pops up at the same time, the left side of the dialog box shows the signal options of the sender control "pushButton_2", and the right side of the dialog box shows the control options of the receiver "MainWindow".

According to the functional requirements, the trigger signal is that the button "pushButton_2" is clicked, and select "clicked ()" from the left side of the dialog box.

In the list of control options for the recipient "MainWindow" on the right side of the dialog box, several custom functions just added are displayed. Select "click_pushButton_2 ()".

Click the button "OK" at the bottom of the dialog box to complete the configuration of the signal / slot connection.

Finally, don't forget to write custom functions in the main program. But this is no longer part of QtDesigner design, and I won't go into detail here.

Similarly, we design: when the button control "pushButton_3" is clicked, the current system date is displayed in the text editing control "lineEdit_1", the current system time is displayed in the text editing control "lineEdit_2", and the prompt is displayed in the text editing control "lineEdit_3". Write a custom function click_pushButton_3 () in the main program and establish a signal / slot connection with "pushButton_3".

This shows that in custom subfunctions, multiple control objects can be manipulated at the same time, and various user-defined functions can be realized.

2.3 connection between signal and slot: the same sender and receiver, and the slot function is the built-in function of the control

This example introduces the operation of the same sender and receiver, and the slot function is the built-in function of the control.

As the name implies, the same sender and receiver means that the sender of the signal and the receiver of the slot function are the same control object. What's going on? For example, a switch button has two states of "On/Off", and the button state is flipped each time it is pressed. Similarly, the option box has two states: selected and unchecked. In particular, after clicking the button, close the button control, which also belongs to the same sender and receiver.

We first change the control object "pushButton_4" from the button control QPushButton to the option box control "QCheckBox":

Click on the control object "pushButton_4", and the border around the control object displays several small blue squares

Click the right mouse button to call out the drop-down menu and select: "variant to"-> "QCheckBox".

At this point, the button control in the design interface window becomes an option box. At the same time, the control "pushButton_4" in the object Viewer on the right is automatically changed to "checkBox_4". The changed control "checkBox_4" inherits some properties of the original control "pushButton_4", such as location, size, and display content.

Next, set the signal / slot connection:

(1) Select the menu item "Edit"-> Edit signal / slot, or enter signal / slot editing mode through the shortcut key F4 or select in the toolbar.

(2) Select the sender of the control object, here is the button control "checkBox_4", press the left mouse button and move, when the mouse moves out of the control object area, there is a red line with arrow and a red grounding symbol.

Long press the left mouse button, drag the mouse back to the "checkBox_4" area of the control object, release the left mouse button, and establish a signal / slot connection in which both the sender and receiver are the control object "checkBox_4".

At this point, the control object "checkBox_4" turns light red, and the red line with arrows starts from "checkBox_4" and returns to the end of "checkBox_4".

(3) the dialog box "configure connection-QtDesigner" pops up at the same time. On the left and right side of the dialog box are the signal and slot function of the control object "checkBox_4", respectively.

Select "clicked (bool)" from the left side of the dialog box

Select "setChecked (bool)" from the right side of the dialog box

Click the button "OK" at the bottom of the dialog box to complete the configuration of the signal / slot connection.

2.4 connection between signal and slot: the sender is the action object

A common signal sender is a variety of control objects in the graphics window, but they can also be action objects. This example describes the connection between signals and slots for control objects in menu bars and toolbars.

When the sender of the signal is an action object, the receiver of the signal is usually the top-level object "MainWindow", and the slot function can be either a built-in function or a custom function of the object "MainWindow".

In the previous article, we established a signal / slot connection for the action "actionQuit" in the menu bar and toolbar, which is a case where the sender is the action object and is connected to the built-in function of the object "MainWindow". The operation process is as follows:

From the "signal / slot Editor" window at the lower right of the QtDesigner, click the green "+" to create a new signal / slot connection

Click "" and select the object "actionQuit" from the menu.

Click "" and select "triggered ()" from the menu.

Click "" and select "MainWindow" from the menu.

Click "" and select "closed ()" from the menu.

The effect of the above operation is that when the sender object "actionQuit" triggers "triggered ()", the receiver object "MainWindow" executes the slot function "closed ()".

Let's establish a signal / slot connection for another action "actionHelp", the slot function of which is the custom function trigger_actHelp (). The operation process is as follows:

Add the custom function trigger_actHelp () to the slot function configuration connection table in QtDesigner

From the "signal / slot Editor" window at the lower right of the QtDesigner, click the green "+" to create a new signal / slot connection

Click "" and select the object "actionHelp" from the menu.

Click "" and select "triggered ()" from the menu.

Click "" and select "MainWindow" from the menu.

Click "" and select "trigger_actHelp ()" from the menu.

So far, this chapter introduces several common methods of editing and setting signal / slot connections with QtDesigner. As shown in the following figure, the signal / slot connections added in QtDesigner are displayed in the signal / slot editor window.

3. The main program of graphical interface

In the previous section, we completed the design of the graphical interface in QtDesigner and saved the file as uiDemo4.ui. Open PyCharm, select the file uiDemo4.ui, and use PyUIC to convert it to uiDemo4.py.

Next, we will write the main program of the graphical interface and call the graphical interface design file uiDemo4.py.

3.1 from process-oriented to object-oriented programming

In the previous article, after we created the main window in the main program, we directly called Ui_MainWindow () in UI. This is a process-oriented programming method.

# GUIdemo3.pyimport uiDemo3 # Import image interface design file if _ _ name__ ='_ main__': app = QApplication (sys.argv) # create application object MainWindow = QMainWindow () # create main window ui = uiDemo3.Ui_MainWindow () ui.setupUi (MainWindow) MainWindow.show () # display main window sys.exit (app.exec_ ()) # in Object-oriented programming for exiting from the main thread

With the deepening of the project, we need to deal with richer graphical interfaces and achieve more complex software functions, the scale of the program is getting larger and larger, and the structure of the program is becoming more and more complex.

Object-oriented programming makes the structure of the program clearer, so it is easy to read, understand, develop and maintain, and is very suitable for the development of large-scale, multi-tasking graphical interface application software. Classes, objects, controls and methods in PyQt5 are all concepts of object-oriented programming. Therefore, from the beginning of this paper, we use the object-oriented programming method to write the main program of the graphical interface.

The routine GUIdemo4.py is as follows:

From uiDemo4 import Ui_MainWindow # Import Ui_MainWindow interface class class MyMainWindow (QMainWindow, Ui_MainWindow) in uiDemo4.py: # inherit QMainWindow class and Ui_MainWindow interface class def _ init__ (self, parent=None): super (MyMainWindow) Self). _ init__ (parent) # initialize parent class self.setupUi (self) # inherit Ui_MainWindow interface class if _ _ name__ = ='_ main__': app = QApplication (sys.argv) # used in QApplication method Create the application object myWin = MyMainWindow () # instantiate the MyMainWindow class, create the main window myWin.show () # end the process in the desktop display control myWin sys.exit (app.exec_ ()) # and exit the program

In the above routine, we created a class MyMainWindow () that inherits the QtWidgets.QMainWindow class method and the Ui_MainWindow interface class in the imported uiDemo4.py.

Super (MyMainWindow, self). Init (): initializes the parent class, converts the MyMainWindow object self to the parent class QMainWindow object, and calls the init function.

Self.setupUi (self): inherits the Ui_MainWindow interface class in uiDemo4.py and calls the setupUi () method of the Ui_MainWindow class.

A rookie who is not familiar with object-oriented programming, it doesn't matter if you don't understand this program, just save it.

3.2 Custom slot function

Run the routine GUIdemo4.py. Why, the report is wrong:

AttributeError: 'MyMainWindow' object has no attribute' click_pushButton_2'

The system prompts that the 'click_pushButton_2', cannot be found because the slot function defined in 2. 2 has not been written in the main program.

Add custom slot functions click_pushButton_2 (), click_pushButton_3, trigger_actHelp (self) to the main program. The complete code of the routine GUIdemo4.py is given below.

# GUIdemo4.py# Demo4 of GUI by PyQt5# Copyright 2021 youcans, XUPT# Crated:2021-10-10import sysfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBoxfrom uiDemo4 import Ui_MainWindow # Import Ui_MainWindow interface class class MyMainWindow (QMainWindow, Ui_MainWindow) in uiDemo4.py: # inherit QMainWindow class and Ui_MainWindow interface class def _ init__ (self, parent=None): super (MyMainWindow Self). _ init__ (parent) # initialize parent class self.setupUi (self) # inherit Ui_MainWindow interface class def click_pushButton_2 (self): # Click pushButton_2 to trigger self.lineEdit_2.setText ("click_pushButton_2") return def click_pushButton_3 (self): # Click pushButton_3 to trigger from datetime import datetime # Guide Enter the datetime library nowDate = datetime.now () .strftime ("% Y-%m-%d") # to get the 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: {}" .form at (nowDate)) # display 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 triggers QMessageBox.about (self "About", "" Digital Image processing Toolbox v1.0\ nCopyright YouCans, XUPT 2021 ") returnif _ _ name__ = ='_ main__': app = QApplication (sys.argv) # is used in the QApplication method Create the application object myWin = MyMainWindow () # instantiate the MyMainWindow class, create the main window myWin.show () # end the process in the desktop display control myWin sys.exit (app.exec_ ()) # and exit the program

Now we have a simple but complete object-oriented graphical interface application GUIdemo4.

Check the features of the application GUIdemo4:

Click the "edit button" to clear "text edit line-1"

Click the "edit button" and display "click_pushButton_2" in "text edit line-2"

Click the "edit button" to display the current date in "text edit line-1", the current time in "text edit line-2", and "Demo4 of GUI by PyQt5" in "text edit line-3"

Click "button", the option box of "button" is selected

Click help in the toolbar, pop up the information prompt box in the above picture, and click "OK" to close the information box.

Click exit in the menu bar or toolbar to close the graphics window application.

If the above tests are successful, congratulations to Xiaobai, you have mastered the basic functions of designing PyQt5 graphical interface with QtDesigner.

This is the end of the article on "how to connect PyQt5 signals and slots in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report