如何重构那些基本类(PyQt5)

2024-04-25 01:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习PyQt5,并尝试创建一个扩展的小部件。 我也在学习面向对象,所以我缺乏这个项目的经验。你知道吗

我的最终目标是拥有能够禁用/启用一些从属小部件的主小部件。 到目前为止,我需要检查和单选按钮。你知道吗

因此,我尝试创建一个抽象类,其中包含小部件的扩展行为(小部件状态的管理):

class QDisablingWidget():
    __metaclass__ = ABCMeta
    def __init__(self):
        self.slaveWidgets = []
        self.slaveStateWhenMasterIsEnabled = {}

    def addSlaveWidget(self, slaveWidget, isEnabledWhenMasterIsEnabled=True):
        [...]
    def updateSlaveStatus(self):
        [...]

然后创建扩展的小部件类:

class QDisablingCheckBox(QtWidgets.QCheckBox, QDisablingWidget):
    def __init__(self, text=None, parent=None, isInMutexGroup=False):
        super(QtWidgets.QCheckBox, self).__init__()
        super(QDisablingWidget, self).__init__()
        if text:
            self.setText(text)
        if parent:
            self.setParent(parent)
        self.isInMutexGroup = isInMutexGroup

        # Click signal handling
        self.stateChanged.connect(self.updateSlaveStatus)


class QDisablingRadioButton(QtWidgets.QRadioButton, QDisablingWidget):
    def __init__(self, text=None, parent=None, isInMutexGroup=False):
        super(QtWidgets.QRadioButton, self).__init__()
        super(QDisablingWidget, self).__init__()
        if text:
            self.setText(text)
        if parent:
            self.setParent(parent)
        self.isInMutexGroup = isInMutexGroup

        # Click signal handling
        self.toggled.connect(self.updateSlaveStatus)

您已经可以看到问题: 我需要将我的self.updateSlaveStatus连接到正确的信号(stateChangedtoggled),所以我将它添加到派生类的构造函数中。 最近,出于某些实现原因,我还添加了isInMutexGroup参数,我意识到我在两个派生类中复制代码。。。你知道吗

这是我第一次尝试使用OOP“真正的”(多重继承和抽象类的第一次尝试),所以即使我知道我打破了OOP概念的美丽,我也不知道该怎么做才能得到一个好的类层次结构。。。你知道吗

所以基本上,我在寻找这个例子的解决方案。但我也寻找指导方针,一般性意见,教程等,其实任何可以帮助我!你知道吗

谢谢你的帮助。你知道吗


Tags: textselfnoneifinit部件def抽象类
1条回答
网友
1楼 · 发布于 2024-04-25 01:39:54

即使我对这个问题投了反对票,我想一些初学者可能会对我找到的解决方案感兴趣:

我的扩展抽象类是这样的:

class QDisablingWidget(QtCore.QObject):
    __metaclass__ = ABCMeta
    def __init__(self, isInMutexGroup=False, **kwds):
        [...]

然后我可以这样派生类:

class QDisablingCheckBox(QtWidgets.QCheckBox, QDisablingWidget):
    def __init__(self, **kwds):
        super().__init__(**kwds)
        # On click signal handling
        self.stateChanged.connect(self.updateSlaveStatus)

以及

class QDisablingRadioButton(QtWidgets.QRadioButton, QDisablingWidget):
    def __init__(self, **kwds):
        super().__init__(**kwds)
        # On click signal handling
        self.toggled.connect(self.updateSlaveStatus)

最后,当我使用类时,我需要创建这样的对象:

disablingRadioBut = QWidgets.QDisablingRadioButton(text="My button",
                                                   parent=self,
                                                   isInMutexGroup=True)

也就是说,我必须显式地使用关键字,这样每个构造器都会吃掉使用/知道的kewords。 由于这种方法,我的扩展类具有最大的可重用性。你知道吗

我得到了这个解决方案: http://pyqt.sourceforge.net/Docs/PyQt5/multiinheritance.html

更多详情请参见: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/

一篇很好的文章!你知道吗

相关问题 更多 >