Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python PyQt Signals and Slots

Python PyQt Signals and Slots

Signals and Slots are the mechanism PyQt uses for communication between objects, and one of the core features of the Qt framework. It provides a flexible, type-safe way for different objects to communicate without knowing each other's implementation details.

In short:


Why do we need signals and slots?

In traditional GUI programming we usually handle user interaction with callbacks. Compared with callbacks, PyQt's signals and slots have the following advantages:

  1. Loose coupling: The object emitting a signal does not need to know which object will receive it
  2. Type Safety: The parameter types of signals and slots are checked when the connection is made
  3. Many-to-many relationships: One signal can connect to many slots, and one slot can receive many signals
  4. Thread Safety: Supports cross-thread communication

Basic Usage

Creating signals

In a custom QObject subclass, you can use pyqtSignal() to define signals:

Example

from

PyQt5.

QtCore

import

QObject

,

pyqtSignal

class

MyEmitter

(

QObject

)

:

   

Define a signal with no arguments

    signal1

=

pyqtSignal

(

)

   

   

Define a signal with a string argument

    signal2

=

pyqtSignal

(

str

)

   

   

Define a signal with multiple arguments

    signal3

=

pyqtSignal

(

int

,

str

)

Emitting signals

Once a signal is defined, you can emit it by calling its emit() method:

Example

emitter

=

MyEmitter

(

)

emitter.

signal1

.

emit

(

)

         

Emit a signal with no arguments

emitter.

signal2

.

emit

(

"Hello"

)

   

Emit a signal with a string argument

emitter.

signal3

.

emit

(

123

,

"abc"

)

Emit a signal with multiple arguments

Creating slot functions

A slot can be any Python callable, usually an instance method:

Example

class

MyReceiver:

   

def

slot1

(

self

)

:

       

print

(

"slot1 called"

)

   

   

def

slot2

(

self

,

text

)

:

       

print

(

f

"slot2 called with: {text}"

)

   

   

def

slot3

(

self

,

number

,

text

)

:

       

print

(

f

"slot3 called with: {number}, {text}"

)

Connecting signals and slots

Use the signal's connect() method to connect the signal to a slot:

Example

emitter

=

MyEmitter

(

)

receiver

=

MyReceiver

(

)

Connecting signals and slots

emitter.

signal1

.

connect

(

receiver.

slot1

)

emitter.

signal2

.

connect

(

receiver.

slot2

)

emitter.

signal3

.

connect

(

receiver.

slot3

)


Practical Application Examples

Example 1: button click event

Example

from

PyQt5.

QtWidgets

import

QApplication

,

QPushButton

,

QVBoxLayout

,

QWidget

def

on_button_clicked

(

)

:

   

print

(

"Button was clicked!"

)

app

=

QApplication

(

[

]

)

window

=

QWidget

(

)

layout

=

QVBoxLayout

(

)

button

=

QPushButton

(

"Click Me"

)

button.

clicked

.

connect

(

on_button_clicked

)

 

Connecting signals and slots

layout.

addWidget

(

button

)

window.

setLayout

(

layout

)

window.

show

(

)

app.

exec_

(

)

Example 2: custom signal

Example

from

PyQt5.

QtCore

import

QObject

,

pyqtSignal

class

Worker

(

QObject

)

:

    progressChanged

=

pyqtSignal

(

int

)

 

Define a signal with an int argument

   

   

def

do_work

(

self

)

:

       

for

i

in

range

(

101

)

:

           

self

.

progressChanged

.

emit

(

i

)

 

Emitting signals

class

Window

(

QWidget

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

worker

=

Worker

(

)

       

self

.

worker

.

progressChanged

.

connect

(

self

.

update_progress

)

       

   

def

update_progress

(

self

,

value

)

:

       

print

(

f

"Progress: {value}%"

)

window

=

Window

(

)

window.

worker

.

do_work

(

)


Advanced usage

Disconnecting

Use disconnect() The method disconnects a signal from a slot:

Example

emitter.

signal1

.

disconnect

(

receiver.

slot1

)

Blocking signals

Temporarily prevent an object from emitting all signals:

Example

emitter.

blockSignals

(

True

)

 

Blocking signals

Signals emitted here will not be delivered

emitter.

blockSignals

(

False

)

Unblock

Signal-slot connection types

PyQt supports several connection types, specified through Qt.ConnectionType :

  1. Qt.AutoConnection (default)
  2. Qt.DirectConnection
  3. Qt.QueuedConnection
  4. Qt.BlockingQueuedConnection
  5. Qt.UniqueConnection

Example

from

PyQt5.

QtCore

import

Qt

emitter.

signal1

.

connect

(

receiver.

slot1

,

Qt.

QueuedConnection

)


Common Problems and Solutions

Problem 1: the signal does not trigger the slot

Possible cause:

  1. The signal and slot are not connected correctly
  2. The receiving object has been destroyed
  3. The signal is blocked

Solution:

  1. Check that the connection code is correct
  2. Make sure the receiving object still exists
  3. Check for code that blocks signals

Problem 2: parameter types do not match

Possible cause: The parameter types or counts of the signal and slot do not match

Solution:

  1. Check the parameter definitions of the signal and slot
  2. Using decorators @pyqtSlot Specify the slot's parameter types explicitly

Example

from

PyQt5.

QtCore

import

pyqtSlot

class

MyReceiver:

   

@

pyqtSlot

(

int

)

   

def

slot

(

self

,

value

)

:

       

print

(

value

)


Best Practices

  1. Use clear names: Give signals and slots descriptive names
  2. Make parameters explicit: Specify the parameter types of signals and slots explicitly
  3. Resource management: Disconnect connections that are no longer needed in time
  4. Thread Safety: For cross-thread communication use QueuedConnection
  5. Document thoroughly: Add docstrings to custom signals and slots

The signals and slots mechanism is at the heart of PyQt programming, and mastering it will greatly improve the efficiency and quality of your GUI development. By practicing these examples and following best practices, you will be able to build responsive, well-structured PyQt applications.