pyqt4 python中的MRO错误

时间:2012-07-04 03:25:53

标签: python pyqt4

我想继承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_()) 

1 个答案:

答案 0 :(得分:3)

Multiple Inheritance in 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()