2. Signals & Slots
The signals and slots mechanism is a core Qt feature used for inter-object communication. A signal is emitted when an event (e.g., a mouse click) occurs and a slot is a Python method or function that gets executed in response. To establish a connection, you must connect() a signal to a slot.
2.1 Basic Signals & Slots Mechanism
![]() |
Your task is to create a button that displays a message in the terminal when clicked. |
Here’s how to do that:
Create a
QPushButtoninstance and add it to the layout.QPushButtonis a widget that emits a signal when you click on it. It also supportspressed(),released()andtoggled()signals. Theclicked()signal combinespressed()andreleased().-
Add a method to the
Windowclass that will act as the slot when the button is clicked. We have decorated it with theSlot()decorator. This optional - omitting it still works, but the Qt documentation recommends it to avoid runtime overhead.Notice the
on_button_clicked()method’s signature includes acheckedparameter, which matches the signature ofQPushButton.clicked()signal, which, in turn, maches the parameter passed to the@Slot()decorator. In this example,checkedwill always be false because the button’scheckableproperty defaults toFalse(and we haven’t changed it).You could simplify the slot declaration and use1 def on_button_clicked(self)if you don’t need the button’s
checkedvalue - it would simply be ignored.1 The slot just prints a message to the terminal, but you can add any code to it (e.g. to update other widgets or save data). -
Connect the signal to the slot using
1 object.signal_name.connect(slot_name)
Note that there are no parentheses after
self.on_button_clicked-connect()expects a function object, not a function call.
Run the script and you’ll see a window with a button that prints a message when you click on it.

2.2 Using Python Lambda Functions
![]() |
Your task is to display a message in the terminal when a button is clicked. |
To do this:
Create the widget. It’s a
QPushButtonlike in the previous example.-
Connect the
QPushButton.clicked()signal to the slot. There are two things to note here:You can connect a signal to a Python lambda function (ie. an anonymous function), instead of a named method,
Lambdas let you pass extra arguments to your slot. In the lambda we call
self.log()passing it an extra string argument (My log message).
When you run the code, clicking the button executes the lambda, which in turn invokes log() that prints two lines to the terminal:
1 Button clicked
2 My log message
If you don’t implement
__init__()in your class at all, the parent class gets initalized automatically.↩︎
