本文介绍了将自定义属性添加到 QCheckBox 小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有(我认为)一个简单的问题,但没有太多运气试图找到答案.pyqt 的新手!

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

我根据多种因素动态地将一些 QtGui.QCheckBox() 小部件添加到 gridLayout.我的问题是,如何向每个 chkbox 小部件添加自定义属性?我想在每个 qt 小部件中存储一些自定义的东西.

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.

干杯

推荐答案

您可以子类化 QCheckBox 类.例如:

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

这里我们覆盖了 __init__ 方法,该方法在您实例化类时自动调用.我们在签名中添加一个额外的参数 my_param,然后将指定的任何参数和关键字参数收集到 argskwargs 中.

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.

在我们新的 __init__ 方法中,我们首先调用原始的 QCheckBox.__init__ 传递对新对象 self 的引用并解包参数是我们捕获的关键字参数.然后我们保存传入一个实例属性的新参数.

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.

现在你有了这个新类,如果你之前通过调用 x = QtGui.QCheckBox('text, parent) 创建(实例化)复选框,你现在会调用 x = MyCheckBox(my_param, 'text', parent) 并且您可以通过 x.custom_param 访问您的参数.

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.

这篇关于将自定义属性添加到 QCheckBox 小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 19:15