Pyqt Signal Slot Emit
Signals and Slots in PySide. From Qt Wiki (Redirected from Signals and slots in PySide) Redirect page. Jump to: navigation, search. Many signals also transmit data, providing information about the state change or widget that fired them. The receiving slot can use this data to perform different actions in response to the same signal. However, there is a limitation: the signal can only emit the data it was designed to.
Introduction
In some applications it is often necessary to perform long-running tasks, such as computations or network operations, that cannot be broken up into smaller pieces and processed alongside normal application events. In such cases, we would like to be able to perform these tasks in a way that does not interfere with the normal running of the application, and ensure that the user interface continues to be updated. One way of achieving this is to perform these tasks in a separate thread to the main user interface thread, and only interact with it when we have results we need to display.
This example shows how to create a separate thread to perform a task - in this case, drawing stars for a picture - while continuing to run the main user interface thread. The worker thread draws each star onto its own individual image, and it passes each image back to the example's window which resides in the main application thread.
The User Interface
We begin by importing the modules we require. We need the math and random modules to help us draw stars.
The main window in this example is just a QWidget. We create a single Worker instance that we can reuse as required.
The user interface consists of a label, spin box and a push button that the user interacts with to configure the number of stars that the thread wil draw. The output from the thread is presented in a QLabel instance, viewer.
We connect the standard finished() and terminated() signals from the thread to the same slot in the widget. This will reset the user interface when the thread stops running. The custom output(QRect, QImage) signal is connected to the addImage() slot so that we can update the viewer label every time a new star is drawn.
The start button's clicked() signal is connected to the makePicture() slot, which is responsible for starting the worker thread.
We place each of the widgets into a grid layout and set the window's title:
Pyqt Signal Slot Emit Generator
The makePicture() slot needs to do three things: disable the user interface widgets that are used to start a thread, clear the viewer label with a new pixmap, and start the thread with the appropriate parameters.
Since the start button is the only widget that can cause this slot to be invoked, we simply disable it before starting the thread, avoiding problems with re-entrancy.
We call a custom method in the Worker thread instance with the size of the viewer label and the number of stars, obtained from the spin box.
Whenever is star is drawn by the worker thread, it will emit a signal that is connected to the addImage() slot. This slot is called with a QRect value, indicating where the star should be placed in the pixmap held by the viewer label, and an image of the star itself:
We use a QPainter to draw the image at the appropriate place on the label's pixmap.
The updateUi() slot is called when a thread stops running. Since we usually want to let the user run the thread again, we reset the user interface to enable the start button to be pressed:
Now that we have seen how an instance of the Window class uses the worker thread, let us take a look at the thread's implementation.
The Worker Thread
The worker thread is implemented as a PyQt thread rather than a Python thread since we want to take advantage of the signals and slots mechanism to communicate with the main application.
We define size and stars attributes that store information about the work the thread is required to do, and we assign default values to them. The exiting attribute is used to tell the thread to stop processing.
Each star is drawn using a QPainterPath that we define in advance:
Before a Worker object is destroyed, we need to ensure that it stops processing. For this reason, we implement the following method in a way that indicates to the part of the object that performs the processing that it must stop, and waits until it does so.
For convenience, we define a method to set up the attributes required by the thread before starting it.
The start() method is a special method that sets up the thread and calls our implementation of the run() method. We provide the render() method instead of letting our own run() method take extra arguments because the run() method is called by PyQt itself with no arguments.
The run() method is where we perform the processing that occurs in the thread provided by the Worker instance:
Information stored as attributes in the instance determines the number of stars to be drawn and the area over which they will be distributed.
We draw the number of stars requested as long as the exiting attribute remains False. This additional check allows us to terminate the thread on demand by setting the exiting attribute to True at any time.
The drawing code is not particularly relevant to this example. We simply draw on an appropriately-sized transparent image.
For each star drawn, we send the main thread information about where it should be placed along with the star's image by emitting our custom output() signal:
Since QRect and QImage objects can be serialized for transmission via the signals and slots mechanism, they can be sent between threads in this way, making it convenient to use threads in a wide range of situations where built-in types are used.
Running the Example
We only need one more piece of code to complete the example:
last modified July 16, 2020
In this part of the PyQt5 programming tutorial, we explore events and signalsoccurring in applications.
Events in PyQt5
GUI applications are event-driven. Events are generated mainly by theuser of an application. But they can be generated by other means as well; e.g. anInternet connection, a window manager, or a timer.When we call the application's exec_()
method, the application entersthe main loop. The main loop fetches events and sends them to the objects.
In the event model, there are three participants:
- event source
- event object
- event target
The event source is the object whose state changes. It generates events.The event object (event) encapsulates the state changes in the event source.The event target is the object that wants to be notified. Event source objectdelegates the task of handling an event to the event target.
PyQt5 has a unique signal and slot mechanism to deal with events.Signals and slots are used for communication between objects. A signalis emitted when a particular event occurs. A slot can be any Python callable.A slot is called when its connected signal is emitted.
PyQt5 signals and slots
This is a simple example demonstrating signals and slots in PyQt5.
In our example, we display a QtGui.QLCDNumber
and a QtGui.QSlider
. We change the lcd
number by dragging the slider knob.
Here we connect a valueChanged
signal of the slider to thedisplay
slot of the lcd
number.
The sender is an object that sends a signal. The receiveris the object that receives the signal. The slot is the method thatreacts to the signal.
PyQt5 reimplementing event handler
Events in PyQt5 are processed often by reimplementing event handlers.
In our example, we reimplement the keyPressEvent()
event handler.
If we click the Escape button, the application terminates.
Event object in PyQt5
Event object is a Python object that contains a number of attributesdescribing the event. Event object is specific to the generated eventtype.
In this example, we display the x and ycoordinates of a mouse pointer in a label widget.
The x and y coordinates are displayd in a QLabel
widget.
Mouse tracking is disabled by default, so the widget only receives mouse moveevents when at least one mouse button is pressed while the mouse is being moved.If mouse tracking is enabled, the widget receives mouse move events evenif no buttons are pressed.
The e
is the event object; it contains data about the eventthat was triggered; in our case, a mouse move event. With the x()
and y()
methods we determine the x and y coordinates ofthe mouse pointer. We build the string and set it to the label widget.
PyQt5 event sender
Sometimes it is convenient to know which widget is the sender of a signal.For this, PyQt5 has the sender
method.
We have two buttons in our example. In the buttonClicked
methodwe determine which button we have clicked by calling thesender()
method.
Both buttons are connected to the same slot.
We determine the signal source by calling the sender()
method.In the statusbar of the application, we show the labelof the button being pressed.
PyQt5 emitting signals
Objects created from a QObject
can emit signals.The following example shows how we to emit custom signals.
We create a new signal called closeApp
. This signal isemitted during a mouse press event. The signal is connected to theclose()
slot of the QMainWindow
.
A signal is created with the pyqtSignal()
as a class attributeof the external Communicate
class.
Pyqt Signal Slot Emit Meter
The custom closeApp
signal is connected to the close()
slot of the QMainWindow
.
When we click on the window with a mouse pointer, the closeApp
signalis emitted. The application terminates.
In this part of the PyQt5 tutorial, we have covered signals and slots.