Search code examples
pyqtattrqwidget

Add custom attribute to QCheckBox widget


I have (I think) a simple question but haven't had much luck trying to find an answer. Really new to pyqt!

I am dynamically adding a number of QtGui.QCheckBox() widgets to a gridLayout based on a number of factors. My question is, how can I add a custom attr to each chkbox widget? I want to store a few custom things inside each qt widget.

Thanks for any help. A basic example would be most useful.

Cheers


Solution

  • You can just subclass the QCheckBox class. For example:

    class MyCheckBox(QtGui.QCheckBox):
        def __init__(self, my_param, *args, **kwargs):
            QtGui.QCheckBox.__init__(self, *args, **kwargs)
            self.custom_param = my_param
    

    Here we override the __init__ method which is called automatically when you instantiate the class. We add an extra parameter my_param to the signature and then collect any arguments and keyword arguments specified into args and kwargs.

    In our new __init__ method, we first call the original QCheckBox.__init__ passing a reference to the new object self and unpacking the arguments are keyword arguments we captured. We then save the new parameter passed in an an instance attribute.

    Now that you have this new class, if you previously created (instantiated) checkbox's by calling x = QtGui.QCheckBox('text, parent) you would now call x = MyCheckBox(my_param, 'text', parent) and you could access your parameter via x.custom_param.