Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading