gpt4 book ai didi

python - PyQt4 中的多窗口

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:57 25 4
gpt4 key购买 nike

我有一个 PyQt 程序用于可视化一些 python 对象。我想显示多个对象,每个对象都在自己的窗口中。

在 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 中,你不需要使用主窗口,除非你想使用停靠栏等。使用对话框将具有相同的效果。

我还可以在您的逻辑中看到一个问题,即您希望父类(super class)调用其子类的构造函数,当然可以是任何类型。我建议你像下面这样重写它:



多窗口类(QtGui.QMainWindow):

def __init__( self ,参数):
self.__windows = []

def addwindow( self ,窗口):
self.__windows.append(窗口)

定义显示():
对于 self.__windows 中的 current_child_window:
current_child_window.exec_() # show 可能会做同样的事情

PlanetApp 类(QtGui.QDialog):
def __init__( self , parent ,行星):
QtGui.QDialog.__init__( self , parent )
# 在这里做很酷的事情

类 AnimalApp(QtGui.QDialog):
def __init__( self , parent ,动物):
QtGui.QDialog.__init__( self , parent )
# 在这里做很酷的事情

如果__name__==“__main__”:
import sys # 这里真的需要这个吗??

app = QtGui.QApplication(sys.argv)

木星= PlanetApp(无,“木星”)
金星= PlanetApp(无,“金星”)
窗口 = 多窗口()
windows.addWindow(木星)
windows.addWindow(金星)

windows.show()
app.exec_()

期望父类(super class)知道要在其子类的 init 中使用的参数不是一个好主意,因为很难确保所有构造函数都相同(也许是动物dialog/window 采用 diff 参数)。

希望对您有所帮助。

关于python - PyQt4 中的多窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1442128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com