Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom attribute to QCheckBox widget

Tags:

attr

pyqt

qwidget

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

like image 609
Nick van Diem Avatar asked Jun 04 '15 19:06

Nick van Diem


2 Answers

You can also use the .setProperty() method, aka Dynamic Properties:

self.the_wdiget.setProperty("my_string", "hello")
self.the_wdiget.setProperty("my_bool", True)
self.the_wdiget.setProperty("my_int", 10)
self.the_wdiget.setProperty("my_stringList", ['sl1', 'sl2', 'sl3'])

# And get it by:

self.the_widget.property("my_bool") # etc.

Strings can also be set to translateable. E.g.

self.the_widget.setProperty("my_string", _translate("Dialog", "hello"))

http://doc.qt.io/qt-5/qobject.html#setProperty

Also see:

http://pyqt.sourceforge.net/Docs/PyQt5/qt_properties.html

like image 162
user3342816 Avatar answered Nov 20 '22 12:11

user3342816


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.

like image 2
three_pineapples Avatar answered Nov 20 '22 12:11

three_pineapples