PyQt4 Python中的MRO错误

3

我想要继承widget1以使用它的方法,但我得到了以下错误:

"TypeError: Error when calling the metaclass bases Cannot create a 
consistent method resolution order (MRO) for bases widget1, QWidget"

当我运行程序时,你能解释一下为什么会出现这种情况吗?
谢谢。
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore, QtGui
import sys

class widget1(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

class widget2(QtGui.QWidget, widget1):
    def __init__(self):
        QtGui.QWidget.__init__(self)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    test = widget1()
    test.show()
    sys.exit(app.exec_()) 

为什么你要同时继承两个类呢? - Ignacio Vazquez-Abrams
@Ignacio Vazquez-Abrams - 我需要从widget2中删除QtGui.QWidget继承吗?因为widget1已经继承了它。 - unice
1个回答

3

PyQt4中的多重继承

不可能定义一个新的Python类,该类从多个Qt类进行子类化。

您可以采用多种替代设计决策,这使得多重QObject继承变得不必要。

简单地从单个父类继承

class widget1(QtGui.QWidget):
    def __init__(self):
        super(widget1, self).__init__()

    def foo(self): pass
    def bar(self): pass

class widget2(widget1):
    def __init__(self):
        super(widget2, self).__init__()

    def foo(self): print "foo"
    def baz(self): pass

组成

class widget2(QtGui.QWidget):
    def __init__(self):
        super(widget2, self).__init__()
        self.widget1 = widget1()

将其中一个类设置为Mixin类,该类不是QObject:

class widget1(QtGui.QWidget):
    def __init__(self):
        super(widget1, self).__init__()

    def foo(self): print "foo"
    def bar(self): pass

class MixinClass(object):
    def someMethod(self):
        print "FOO"

class widget2(widget1, MixinClass):
    def __init__(self):
        super(widget2, self).__init__()

    def bar(self): self.foo()
    def baz(self): self.someMethod()

在第一和第三个示例中,Widget1和Widget2都可以从同一个BaseWidget类继承。 - jfs
@J.F.Sebastian:虽然那似乎是第四个例子。 - jdi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接