PyQt QTableWidgetItem 子类的初始化方法 [英] Init method for subclass of PyQt QTableWidgetItem

查看:97
本文介绍了PyQt QTableWidgetItem 子类的初始化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 QTableWidgetItem 进行子类化,以便我的子类可以有一个额外的 'id' 属性.

I'd like to subclass the QTableWidgetItem so that my subclass can have an additional 'id' attribute.

不幸的是,我有点困惑,因为 PyQt 文档 此处 显示四种不同的 init 方法.

Unfortunately, I'm a little confused because the PyQt docs here show four different init methods.

要为我的QTableWidgetItemWithId"子类创建我自己的 init 方法(它还会传入一个额外的id"参数),我应该使用 *args、**kwargs 吗?如果是这样,正确的语法是什么?

To create my own init method for my "QTableWidgetItemWithId" subclass (which would also pass in an extra 'id' argument), should I be using *args, **kwargs? If so, what would be the correct syntax?

非常感谢

推荐答案

我认为这在一定程度上取决于您的品味、您认为可读的内容以及您希望保持子类的灵活性.您可以向构造函数添加任何您想要的内容,并将所需的内容交给 QTableWidgetItem 的构造函数.有很多方法可以做到.我个人尽量避免使用 *args 和 **kwargs.

I'd say that depends a little on your taste and what you consider readable and also how flexible you want to keep your subclass. You can add whatever you wish to your constructor and just hand what's needed to QTableWidgetItem's constructor. There are many ways of doing it. I personally try to avoid *args and **kwargs when possible.

from PyQt4.QtGui import QTableWidgetItem

class ATableWidgetItem(QTableWidgetItem):

    def __init__(self, id, *args, **kwargs):
        super(ATableWidgetItem, self).__init__(*args, **kwargs)
        self.id = id

a = ATableWidgetItem(0)
b = ATableWidgetItem(0, QTableWidgetItem.UserType)
c = ATableWidgetItem(0, "text", type=QTableWidgetItem.UserType) 

class AnotherTableWidgetItem(QTableWidgetItem):

    def __init__(self, id):
        super(AnotherTableWidgetItem, self).__init__()
        self.id = id

d = AnotherTableWidgetItem(0)

class YetAnotherTableWidgetItem(QTableWidgetItem):

    def __init__(self, id, text="", type=QTableWidgetItem.Type):
        super(YetAnotherTableWidgetItem, self).__init__(text, type)
        self.id = id

e = YetAnotherTableWidgetItem(0)
f = YetAnotherTableWidgetItem(0, "Hello")
g = YetAnotherTableWidgetItem(0, "Hello", QTableWidgetItem.UserType)  

这篇关于PyQt QTableWidgetItem 子类的初始化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆