Transmitting extra data with Qt Signals
Modifying widget signals to pass contextual information to slots

Extended UI features course

Signals are a neat feature of Qt that allow you to pass messages between different components in your applications. Signals are connected to slots which are functions (or methods) which will be run every time the signal fires. 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. So for example, a QAction has a .triggered that fires when that particular action has been activated. The triggered signal emits a single piece of data -- the checked state of the action after being triggered.

For non-checkable actions, this value will always be False

The receiving function does not know which QAction triggered it, or receiving any other data about it.

This is usually fine. You can tie a particular action to a unique function which does precisely what that action requires. Sometimes however you need the slot function to know more than that QAction is giving it. This could be the object the signal was triggered on, or some other associated metadata which your slot needs to perform the intended result of the signal.

This is a powerful way to extend or modify the built-in signals provided by Qt.

Intercepting the signal

Instead of connecting signal directly to the target function, you instead use an intermediate function to intercept the signal, modify the signal data and forward that on to your actual slot function.

This slot function must accept the value sent by the signal (here the checked state) and then call the real slot, passing any additional data with the arguments.

python
def fn(checked):
    self.handle_trigger(checked, <additional args>)

Rather than defining this intermediate function, you can also achieve the same thing using a lambda function. As above, this accepts a single parameter checked and then calls the real slot.

python
lambda checked: self.handle_trigger(checked, <additional args>)

In both examples the <additional args> can be replaced with anything you want to forward to your slot. In the example below we're forwarding the QAction object action to the receiving slot.

python
action = QAction()
action.triggered.connect( lambda checked: self.handle_trigger(checked, action) )

Our handle_trigger slot method will receive both the original checked value and the QAction object. Or receiving slot can look something like this

python
# a class method.
def handled_trigger(self, checked, action):
    # do something here.

Below are a few examples using this approach to modify the data sent with the MainWindow.windowTitleChanged signal.

python
from PySide2.QtWidgets import (
    QApplication, QMainWindow
)
from PySide2.QtCore import Qt

import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        # SIGNAL: The connected function will be called whenever the window
        # title is changed. The new title will be passed to the function.
        self.windowTitleChanged.connect(self.on_window_title_changed)

        # SIGNAL: The connected function will be called whenever the window
        # title is changed. The new title is discarded and the
        # function is called without parameters.
        self.windowTitleChanged.connect(lambda x: self.on_window_title_changed_no_params())

        # SIGNAL: The connected function will be called whenever the window
        # title is changed. The new title is discarded and the
        # function is called without parameters.
        # The function has default params.
        self.windowTitleChanged.connect(lambda x: self.my_custom_fn())

        # SIGNAL: The connected function will be called whenever the window
        # title is changed. The new title is passed to the function
        # and replaces the default parameter. Extra data is passed from
        # within the lambda.
        self.windowTitleChanged.connect(lambda x: self.my_custom_fn(x, 25))

        # This sets the window title which will trigger all the above signals
        # sending the new title to the attached functions or lambdas as the
        # first parameter.
        self.setWindowTitle("My Signals App")

    # SLOT: This accepts a string, e.g. the window title, and prints it
    def on_window_title_changed(self, s):
        print(s)

    # SLOT: This is called when the window title changes.
    def on_window_title_changed_no_params(self):
        print("Window title changed.")

    # SLOT: This has default parameters and can be called without a value
    def my_custom_fn(self, a="HELLLO!", b=5):
        print(a, b)


app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

The .setWindowTitle call at the end of the __init__ block changes the window title and triggers the .windowTitleChanged signal, which emits the new window title as a str. We've attached a series of intermediate slot functions (as lambda functions) which modify this signal and then call our custom slots with different parameters.

Running this produces the following output.

bash
My Signals App
Window title changed.
HELLLO! 5
My Signals App 5
My Signals App 25

The intermediate functions can be as simple or as complicated as you like -- as well as discarding/adding parameters, you can also perform lookups to modify signals to different values.

In the following example a checkbox signal Qt.Checked or Qt.Unchecked is modified by an intermediate slot into a bool value.

python
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QCheckBox
)
from PySide2.QtCore import Qt

import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        checkbox = QCheckBox("Check?")

        # Option 1: conversion function
        def checkstate_to_bool(state):
            if state == Qt.Checked:
                return self.result(True)

            return self.result(False)

        checkbox.stateChanged.connect(checkstate_to_bool)

        # Option 2: dictionary lookup
        _convert = {
            Qt.Checked: True,
            Qt.Unchecked: False
        }

        checkbox.stateChanged.connect(
            lambda v: self.result(_convert[v])
        )

        self.setCentralWidget(checkbox)

    # SLOT: Accepts the check value.
    def result(self, v):
        print(v)


app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

In this example we've connected the .stateChange signal to result in two ways -- a) with a intermediate function which calls the .result method with True or False depending on the signal parameter, and b) with a dictionary lookup within an intermediate lambda.

Running this code will output True or False to the command line each time the state is changed (once for each time we connect to the signal).

QCheckbox triggering 2 slots, with modified signal data QCheckbox triggering 2 slots, with modified signal data

Create GUI Applications with Python & Qt6
The easy way to create desktop applications

My complete guide, updated for 2021 & PySide6. Everything you need build real apps.

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

Trouble with loops

One of the most common reasons for wanting to connect signals in this way is when you're building a series of objects and connecting signals programmatically in a loop. Unfortunately then things aren't always so simple.

If you try and construct intercepted signals while looping over a variable, and want to pass the loop variable to the receiving slot, you'll hit a problem. For example, in the following code we create a series of buttons, and use a intermediate function to pass the buttons value (0-9) with the pressed signal.

python
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QAction, QPushButton,
    QWidget, QLabel, QVBoxLayout, QHBoxLayout
)

import sys


class Window(QWidget):

    def __init__(self):
        super().__init__()

        v = QVBoxLayout()
        h = QHBoxLayout()

        for a in range(10):
            button = QPushButton(str(a))
            button.pressed.connect(
                lambda: self.button_pressed(a)
            )
            h.addWidget(button)

        v.addLayout(h)
        self.label = QLabel("")
        v.addWidget(self.label)
        self.setLayout(v)

    def button_pressed(self, n):
        self.label.setText(str(n))


app = QApplication(sys.argv)
w = Window()
w.show()
app.exec_()

If you run this you'll see the problem -- no matter which button you click on you get the same number (9) shown on the label. Why 9? It's the last value of the loop.

The problem is the line lambda: self.button_pressed(a) where we pass a to the final button_pressed slot. In this context, a is bound to the loop.

python
for a in range(10):
    # .. snip ...
    button.pressed.connect(
        lambda: self.button_pressed(a)
    )
    # .. snip ...

We are not passing the value of a when the button is created, but whatever value a has when the signal fires. Since the signal fires after the loop is completed -- we interact with the UI after it is created -- the value of a for every signal is the final value that a had in the loop: 9.

So clicking any of them will send 9 to button_pressed

The solution is to pass the value in as a (re-)named parameter. This binds the parameter to the value of a at that point in the loop, creating a new, un-connected variable. The loop continues, but the bound variable is not altered.

This ensures the correct value whenever it is called.

python
lambda val=a: self.button_pressed(val)

You don't have to rename the variable, you could also choose to use the same name for the bound value.

python
lambda a=a: self.button_pressed(a)

The important thing is to use named parameters. Putting this into a loop, it would look like this:

python
for a in range(10):
    button = QPushButton(str(a))
    button.pressed.connect(
        lambda val=a: self.button_pressed(val)
    )

Running this now, you will see the expected behavior -- with the label updating to a number matching the button which is pressed.

The working code is as follows:

python
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QAction, QPushButton,
    QWidget, QLabel, QVBoxLayout, QHBoxLayout
)

import sys


class Window(QWidget):

    def __init__(self):
        super().__init__()

        v = QVBoxLayout()
        h = QHBoxLayout()

        for a in range(10):
            button = QPushButton(str(a))
            button.pressed.connect(
                lambda val=a: self.button_pressed(val)
            )
            h.addWidget(button)

        v.addLayout(h)
        self.label = QLabel("")
        v.addWidget(self.label)
        self.setLayout(v)

    def button_pressed(self, n):
        self.label.setText(str(n))


app = QApplication(sys.argv)
w = Window()
w.show()
app.exec_()
Complete Mark As Complete Next

Continue reading

QComboBox  pyside

The QComboBox is a simple widget for presenting a list of options to your users in PyQt, taking up the minimum amount of screen space. The widget can have a single selected item, which is displayed in the widget area. When selected a QComboBox pops out a list of possible values from which you can select. A QComboBox can also - optionally - be made editable, so your users can enter their own values onto the list of possible values. QComboBox in its closed and open state Populating a QComboBox Items can be added or inserted to a QComboBox, where adding appends the item to the end of the current list, while insert inserts them in a specific index in the existing list. There are convenience methods for adding multiple items to a combobox and also for adding icons to the list. The following example will demonstrate each of these using a series of comboboxes. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication, QWidget, QVBoxLayout from PyQt5.QtGui import QIcon import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() combobox1 = QComboBox() combobox1.addItem('One') combobox1.addItem('Two') combobox1.addItem('Three') combobox1.addItem('Four') combobox2 = QComboBox() combobox2.addItems(['One', 'Two', 'Three', 'Four']) combobox3 = QComboBox() combobox3.addItems(['One', 'Two', 'Three', 'Four']) combobox3.insertItem(2, 'Hello!') combobox4 = QComboBox() combobox4.addItems(['One', 'Two', 'Three', 'Four']) combobox4.insertItems(2, ['Hello!', 'again']) combobox5 = QComboBox() icon_penguin = QIcon('animal-penguin.png') icon_monkey = QIcon('animal-monkey.png') icon_bauble = QIcon('bauble.png') combobox5.addItem(icon_penguin, 'Linux') combobox5.addItem(icon_monkey, 'Monkeyix') combobox5.insertItem(1, icon_bauble, 'Baublix') layout = QVBoxLayout() layout.addWidget(combobox1) layout.addWidget(combobox2) layout.addWidget(combobox3) layout.addWidget(combobox4) layout.addWidget(combobox5) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def current_text_changed(self, s): print("Current text: ", s) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() Run the example and compare the result with each series of add and insert steps. Adding items to a QComboBox You can replace the text at a specific index in the list by calling .setItemText() for example. python widget.setItemText(3, 'new text') Finally, you can clear a QComboBox -- removing all items in it -- by calling .clear(). python widget.clear() QComboBox signals The QComboBox emits a number of signals on state changes. When the currently selected item changes, the widget emits .currentIndexChanged() and .currentTextChanged() signals. The first receives the index of the selected entry while the second receives the text of that item. There is a further signal .activated() which is emitted for user-selections whether the index is changed or not: selecting the same entry again will still emit the signal. Highlighting an entry in the QComboBox popup list will emit the .highlighted() signal. The following example demonstrates these signals in action. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() combobox = QComboBox() combobox.addItems(['One', 'Two', 'Three', 'Four']) # Connect signals to the methods. combobox.activated.connect(self.activated) combobox.currentTextChanged.connect(self.text_changed) combobox.currentIndexChanged.connect(self.index_changed) self.setCentralWidget(combobox) def activated(Self, index): print("Activated index:", index) def text_changed(self, s): print("Text changed:", s) def index_changed(self, index): print("Index changed", index) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() If you run the example the signals emitted as you interact with the QComboBox will be shown in the console, giving output like that shown below. Note that when re-selecting the same entry, only the .activated() signal is emitted. python Index changed 1 Text changed: Two Activated index: 1 Index changed 2 Text changed: Three Activated index: 2 Index changed 3 Text changed: Four Activated index: 3 Activated index: 3 Activated index: 3 Getting the current state In addition to the signals, QComboBox has a few methods for getting the current state at any time. For example, you can use .currentIndex() to get the index of the currently selected item in the combobox, or use .currentText() to get the text. With the index you can also look up the text of a specific item using .itemText(). Finally, you can use .count() to get the total number of items in the combobox list. In the example below, we use the activated signal we've already seen to hook up a number of methods which get information about the combobox and display this in the console. As you select any item in the combobox every method will run printing a message to the console. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() # Keep a reference to combobox on self, so we can access it in our methods. self.combobox = QComboBox() self.combobox.addItems(['One', 'Two', 'Three', 'Four']) # Connect signal to our methods. self.combobox.activated.connect(self.check_index) self.combobox.activated.connect(self.current_text) self.combobox.activated.connect(self.current_text_via_index) self.combobox.activated.connect(self.current_count) self.setCentralWidget(self.combobox) def check_index(self, index): cindex = self.combobox.currentIndex() print(f"Index signal: {index}, currentIndex {cindex}") def current_text(self, _): # We receive the index, but don't use it. ctext = self.combobox.currentText() print("Current text", ctext) def current_text_via_index(self, index): ctext = self.combobox.itemText(index) # Get the text at index. print("Current itemText", ctext) def current_count(self, index): count = self.combobox.count() print(f"Index {index+1}/{count}") app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() Running this and selecting different items in the combobox will show the outputs. python Current text Two Current itemText Two Index 1/4 Index signal: 2, currentIndex 2 Current text Three Current itemText Three Index 2/4 Index signal: 3, currentIndex 3 Current text Four Current itemText Four Index 3/4 Editable comboboxes You can set a QComboBox to be editable allowing the user to type enter the values not currently in the list. Entered values can be added to the list, or just used as a value which is not inserted. To enable editing you can call .setEditable(True) on the widget, while control of how inserts operate is handled through the insert policy. This is set by calling .setInsertPolicy() passing one of the following flags: Flag Value Behavior QComboBox.NoInsert 0 No insert QComboBox.InsertAtTop 1 Insert as first item QComboBox.InsertAtCurrent 2 Replace currently selected item QComboBox.InsertAtBottom 3 Insert after last item QComboBox.InsertAfterCurrent 4 Insert after current item QComboBox.InsertBeforeCurrent 5 Insert before current item QComboBox.InsertAlphabetically 6 Insert in alphabetical order For PyQt6 use the fully-qualified flag name, i.e. QComboBox.InsertPolicy.NoInsert For example, to insert new values alphabetically, you would use. python widget.setInsertPolicy(QComboBox.InsertAlphabetically) If the combobox is set to be editable, but QComboBox.NoInsert is set as the insert policy, users will be able to enter their own custom values, but they will not be added to the list. In the following example we have two QComboBox widgets: one which is our editable box and the second which controls the insert policy of the first. Note that since the values of the flags (see above) are just numbers from 0 to 6, we can use the index to determine the flag. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication, QWidget, QVBoxLayout import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() # Keep a reference to combobox on self, so we can access it in our methods. self.combobox = QComboBox() self.combobox.addItems(['One', 'Two', 'Three', 'Four']) self.combobox.setEditable(True) self.combobox.currentTextChanged.connect(self.current_text_changed) # Insert policies self.insertpolicy = QComboBox() self.insertpolicy.addItems([ 'NoInsert', 'InsertAtTop', 'InsertAtCurrent', 'InsertAtBottom', 'InsertAfterCurrent', 'InsertBeforeCUrrent', 'InsertAlphabetically' ]) # The index in the insertpolicy combobox (0-6) is the correct flag value to set # to enable that insert policy. self.insertpolicy.currentIndexChanged.connect(self.combobox.setInsertPolicy) layout = QVBoxLayout() layout.addWidget(self.combobox) layout.addWidget(self.insertpolicy) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def current_text_changed(self, s): print("Current text: ", s) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() If you run this example you'll notice you can now type into the (top) editable combobox and submit them by pressing Enter. The .currentTextChanged() signal will be emitted as you type into the field. python Current text: w Current text: wq Current text: wqe Current text: wqew Current text: wqeww Current text: wqewwq Current text: wqewwqe By default the insert policy is set to QComboBox.NoInsert so entered values will not be added, just set as the value of the combobox. By selecting the insert policy in the second combobox you can change this behavior, having new entries added to the list. Editing a QComboBox with insert policy When you allow users to add values to the list, you may wish to constrain the maximum number of entries. This can be done using .setMaxCount, e.g. python widget.setMaxCount(10) More