题
我有用于显现一些Python对象PyQt的程序。我想这样做显示多个对象,每个对象在自己的窗口。
什么是实现PyQt4的多窗口应用程序的最佳方法是什么?
目前我有以下:
from PyQt4 import QtGui
class MainWindow(QtGui.QMainWindow):
windowList = []
def __init__(self, animal):
pass
def addwindow(self, animal)
win = MainWindow(animal)
windowList.append(win)
if __name__=="__main__":
import sys
app = QtGui.QApplication(sys.argv)
win = QMainWindow(dog)
win.addWindow(fish)
win.addWindow(cat)
app.exec_()
但是,这种方法并不理想,当我试图分析出在它自己的类MultipleWindows一部分,我面对的问题。例如:
class MultiWindows(QtGui.QMainWindow):
windowList = []
def __init__(self, param):
raise NotImplementedError()
def addwindow(self, param)
win = MainWindow(param) # How to call the initializer of the subclass from here?
windowList.append(win)
class PlanetApp(MultiWindows):
def __init__(self, planet):
pass
class AnimalApp(MultiWindows):
def __init__(self, planet):
pass
if __name__=="__main__":
import sys
app = QtGui.QApplication(sys.argv)
win = PlanetApp(mercury)
win.addWindow(venus)
win.addWindow(jupiter)
app.exec_()
将上面的代码调用MainWindow类的初始化,而不是适宜亚类的,因此将抛出异常。
我如何可以调用子类的初始化?有没有更优雅的方式来做到这一点?
解决方案
为什么不使用对话框?在Qt你不需要,除非你想用码头等使用的主窗口..使用对话框都会有同样的效果。
我还可以看到关于您希望超类中调用它的孩子,当然也可以是任何类型的构造函数的事实,在你的逻辑存在问题。我建议你把它改写如下所示:
class MultiWindows(QtGui.QMainWindow):
def __init__(self, param):
self.__windows = []
def addwindow(self, window):
self.__windows.append(window)
def show():
for current_child_window in self.__windows:
current_child_window.exec_() # probably show will do the same trick
class PlanetApp(QtGui.QDialog):
def __init__(self, parent, planet):
QtGui.QDialog.__init__(self, parent)
# do cool stuff here
class AnimalApp(QtGui.QDialog):
def __init__(self, parent, animal):
QtGui.QDialog.__init__(self, parent)
# do cool stuff here
if __name__=="__main__":
import sys # really need this here??
app = QtGui.QApplication(sys.argv)
jupiter = PlanetApp(None, "jupiter")
venus = PlanetApp(None, "venus")
windows = MultiWindows()
windows.addWindow(jupiter)
windows.addWindow(venus)
windows.show()
app.exec_()
这不是一个很好的主意,期待超类知道该参数将在的init 及其子类的使用,因为它是真的很难确保所有的构造将是相同的(也许是动物对话框/窗口占据DIFF参数)。
希望它能帮助。
其他提示
为了引用一个从超类继承的内部超类亚类中,我使用self.__class__()
,所以MultiWindows类原先为:
class MultiWindows(QtGui.QMainWindow):
windowList = []
def __init__(self, param):
raise NotImplementedError()
def addwindow(self, param)
win = self.__class__(param)
windowList.append(win)
不隶属于 StackOverflow