(PyQT) How do I get which element triggered a callback function when many elements are connected to that callback function?

my code looks something like this:

for i in range(num_boxes):
    box = QCheckBox(self.row)
    box.setObjectName(f"{i}")
    box.setText(f"{i}")
    box.stateChanged.connect(checkbox_callback)

So I dynamically generate checkboxes and link them all up to a single callback function which looks something like this:

def checkbox_callback(state):
    print(state)

I am now wondering how I can check which of my checkboxes has triggered the callback function, because to my knowledge, I can only get the state of the box that triggered the event, but not the box itself, which is mandatory for my purposes.

I hope I made myself clear and thanks in advance.

>Solution :

The most basic way is to pass the widget as part of the callback.

from functools import partial

for i in range(num_boxes):
    box = QCheckBox(self.row)
    box.setObjectName(f"{i}")
    box.setText(f"{i}")
    box.stateChanged.connect(partial(checkbox_callback, widget=box))

def checkbox_callback(state, widget):
    print(widget.text(), state)

Alternatively you could subclass the widget to make a custom signal.

class MyCheckBox(QCheckBox):

    customStateChanged = Signal(QCheckBox, Qt.CheckState)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.stateChanged.connect(self.onStateChange)
    
    @Slot(Qt.CheckState)
    def onStateChange(self, checkState):
        self.customStateChanged.emit(self, checkState)

Leave a Reply