问题描述
我正在尝试创建一组继承QWidget,QMainWindow和QDialog的PySide类.另外,我想继承另一个类以覆盖一些功能,并设置小部件的布局.
I'm trying to create a set of PySide classes that inherit QWidget, QMainWindow, and QDialog. Also, I would like to inherit another class to overrides a few functions, and also set the layout of the widget.
示例:
Mixin:
class Mixin(object):
def __init__(self, parent, arg):
self.arg = arg
self.parent = parent
# Setup the UI from QDesigner
ui = Ui_widget()
ui.setupUi(self.parent)
def setLayout(self, layout, title):
self.parent.setWindowTitle(title)
self.parent.setLayout(layout)
def doSomething(self):
# Do something awesome.
pass
小部件:
class Widget(Mixin, QtGui.QWidget):
def __init__(self, parent, arg):
super(Widget, self).__init__(parent=parent, arg=arg)
这行不通,但是通过合成可以做到这一点
This won't work, but doing this through composition works
小部件(组成):
class Widget(QtGui.QWidget):
def __init__(self, parent, arg):
super(Widget, self).__init__(parent=parent)
mixin = Mixin(parent=self, arg=arg)
self.setLayout = mixin.setLayout
self.doSomething = mixin.doSomething
我想尝试让小部件继承所有内容,而不是通过合成来完成其中的一部分.谢谢!
I would like to try to have the widget inherit everything instead of having part of it done through composition. Thanks!
推荐答案
保留class Widget(Mixin, QtGui.Widget):
,但在Mixin.__init__
中添加super
调用.这应该确保同时调用Mixin
和QWidget
的__init__
方法,并且首先在Widget
的MRO中找到setLayout
方法的Mixin
实现.
Keep class Widget(Mixin, QtGui.Widget):
, but add a super
call in Mixin.__init__
. This should ensure the __init__
method of both Mixin
and QWidget
are called, and that the Mixin
implementation of the setLayout
method is found first in the MRO for Widget
.
class Mixin(object):
def __init__(self, parent=None, arg=None):
super(Mixin, self).__init__(parent=parent) # This will call QWidget.__init__
self.arg = arg
self.parent = parent
# Setup the UI from QDesigner
ui = Ui_widget()
ui.setupUi(self.parent)
def setLayout(self, layout, title):
self.parent.setWindowTitle(title)
self.parent.setLayout(layout)
def doSomething(self):
# Do something awesome.
pass
class Widget(Mixin, QtGui.QWidget):
def __init__(self, parent, arg):
super(Widget, self).__init__(parent=parent, arg=arg) # Calls Mixin.__init__
这篇关于PySide多重继承:继承QWidget和Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!