Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MRO error in pyqt4 python

Tags:

python

pyqt4

I want to inherit widget1 to use its methods but I get :

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

when I run the program. Can you explain to me why this happen?

thank.

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_()) 
like image 717
unice Avatar asked May 19 '26 17:05

unice


1 Answers

Multiple Inheritance in PyQt4

It is not possible to define a new Python class that sub-classes from more than one Qt class.

There are multiple alternative design decisions you can use, which makes multiple QObject inheritance unnecessary.

Simple inherit from the single parent class

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

Composition

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

Make one of the classes a mixin class, which is not a 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()
like image 69
jdi Avatar answered May 22 '26 07:05

jdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!