pyQt4 and inheritance
For a number of reasons I am contemplating redoing an program I use at work in pyqt4 (at present it is in pygtk). After playing around with it and getting a feel for it and appreciating its philosophy with gui building I am running into some annoying ... bugs or implementation limitations
One of them is inheritance:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication(sys.argv)
class A(object):
def __init__(self):
print "A init"
class B(A):
def __init__(self):
super(B,self).__init__()
print "B init"
class C(QtGui.QMainWindow):
def __init__(self):
super(C,self).__init__()
print "C init"
class D(QtGui.QMainWindow,A):
def __init__(self):
print "D init"
super(D,self).__init__()
print "nsingle class, no inheritance"
A()
print "nsingle class with inheritance"
B()
print "nsingle class with Qt inheritance"
C()
print "nsingle class with Qt inheritance + one other"
D()
If I run this I get:
$ python test.py
single class, no inheritance
A init
single class with inheritance
A init
B init
single class with Qt inheritance
C init
single class with Qt inheritance + one other
D init
while I was expecting:
$ python test.py
single class, no inheritance
A init
single class with inheritance
A init
B init
single class with Qt inheritance
C init
single class with Qt inheritance + one other
D init
A init
Why is it that you cannot use super to initialise the inherited classes when a qt4 class is involved? I would rather not have todo
QtGui.QMainWindow.__init__()
A.__init__()
Anyone know what is going on?
This is not a QT issue, but a lack of understanding of how multiple inheritance works. You can absolutely use multiple inheritance, but it is a tricky subject in Python.
In a nutshell, in your last example, the first __init__
is called, so if you changed class D(QtGui.QMainWindow,A):
to class D(A, QtGui.QMainWindow):
you would see A
's constructor called, and not QMainWindow
's one.
See the following links for further reference on super()
behavior with multiple inheritance:
上一篇: ttk tkinter python3多个框架/窗口
下一篇: pyQt4和继承