pyqt5和多重继承 [英] pyqt5 and multiple inheritance
问题描述
我想创建一个新类,该类继承QWidget的两个子类.我知道在pyqt中不可能实现多重继承,但是如何在一个子类中同时拥有两个父类的属性?
I'd like to create a new class that inherits two subclasses of QWidget. I know multi-inheritance isn't possible in pyqt, but how could I manage to have the properties of both parent classes in one subclass?
我希望我能做的如下:
class A(QWidget):
def __init__(self, widget, parent=None):
widget.destroyed.connect(self.destroy_handler)
@pyqtSlot()
def destroy_handler(self):
pass
class B (A, QStatusBar):
def __init__(self, widget, parent=None):
A.__init__(self, widget)
QStatusBar.__init__(self, parent)
@pyqtSlot()
def destroyed_handler(self):
print("Destroyed")
推荐答案
我终于找到了解决方法:首先,问题来自A和QStatusBar继承QWidget.我们无法更改QStatusBar,因此必须更改A. A不应继承QWidget:因此,让我们创建另一个类AInterface,如下所示:
I finally found how to do it: first of all, the problems came from A and QStatusBar inheriting QWidget. We can't change QStatusBar, so we must changer A. A shouldn't inherit QWidget: so let's create another class, AInterface, like that:
class AInterface(QObject):
def __init__(self, a, parent=None)
super().__init__(parent=parent)
self.a = a
self.connect_signal()
def connect_signal(self, widget):
widget.destroyed.connect(self.handler)
@pyqtSlot()
def handler(self):
self.a.handler()
A现在具有以下实现:
A has now the following implementation:
class A:
def __init__(self, widget):
a.widget = widget
a.interface = AInterface(self)
def handler(self):
pass
因此,现在我们可以创建不仅继承A而且继承任何QObject的子类,如下所示:
Thus, now we can create subclasses inheriting not only A but also any QObject, like this:
class B(QStatusBar, A):
def __init__(self, widget, parent=None):
QStatusBar.__init__(self, parent=parent, wiget=widget)
A.__init__(self, widget)
def handler(self):
self.show('Destroyed', 3000)
请注意QStatusBar的构造函数中的widget=widget
:如果我们未指定它,则会引发TypeError ...
Notice the widget=widget
in the constructor of QStatusBar: if we don't specify it, a TypeError is thrown...
这篇关于pyqt5和多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!