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

An icon of a clipboard-list1

Your task is to create a button that displays a message in the terminal when clicked.

Here’s how to do that:

  1. Create a QPushButton instance and add it to the layout. QPushButton is a widget that emits a signal when you click on it. It also supports pressed(), released() and toggled() signals. The clicked() signal combines pressed() and released().

  2. Add a method to the Window class that will act as the slot when the button is clicked. We have decorated it with the Slot() 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 a checked parameter, which matches the signature of QPushButton.clicked() signal, which, in turn, maches the parameter passed to the @Slot() decorator. In this example, checked will always be false because the button’s checkable property defaults to False (and we haven’t changed it).You could simplify the slot declaration and use

    1 def on_button_clicked(self)
    

    if you don’t need the button’s checked value - 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).

  3. 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

An icon of a clipboard-list1

Your task is to display a message in the terminal when a button is clicked. QPushButton.clicked() doesn’t support passing additional parameters so you decide to use a lambda function.

To do this:

  1. Create the widget. It’s a QPushButton like in the previous example.

  2. 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

  1. If you don’t implement __init__() in your class at all, the parent class gets initalized automatically.↩︎