在我的程序中,我想定义不同的视图来显示我的数据。在我的第一次尝试中,所有视图都在类(QtGui.QWidget)中定义。然而,由于视图的代码开始变得更长,而且我还想添加交互功能,我想将不同的视图分离到单独的类中。
下面是我的第一次尝试。在这里,我只是尝试setCentralWidget
在两个视图之间切换。在切换到每个视图之前,我必须生成视图的新实例。否则我会产生一个运行时错误。似乎每个 View 实例一旦不在中心视图中就会被销毁。
我理解对吗?建议的代码结构是否可以,或者如果我这样构造我的代码会出现问题吗?针对此类问题的任何其他建议/最佳实践?
import sys
from PyQt4 import QtGui
class View1Widget(QtGui.QWidget):
pass
# Describse View 1 of Data
class View2Widget(QtGui.QWidget):
pass
# Describse View 2 of Data
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.main_widget = QtGui.QWidget(self)
# Generate Instances of both views
self.View1 = View1Widget( self.main_widget)
self.View2 = View2Widget( self.main_widget)
# Init Central View
self.setCentralWidget(self.View1)
# Focus
self.main_widget.setFocus()
self.views_menu = QtGui.QMenu('&Views', self)
self.views_menu.addAction('View 1', self.showView1)
self.views_menu.addAction('View 2', self.showView2)
self.menuBar().addMenu(self.views_menu)
def showView1(self):
"Switches Central Widget to View1"
self.View1 = View1Widget( self.main_widget) # Without this line, I would generate a runtime error
self.setCentralWidget(self.View1)
def showView2(self):
"Switches Central Widget to View2"
self.View2 = View2Widget( self.main_widget) # Without this line, I would generate a runtime error
self.setCentralWidget(self.View2)
if __name__ == '__main__':
qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())
如果没有标记线,我会在单击查看 2 而不是返回查看 1 后收到以下运行时错误
Exception "unhandled RuntimeError"
wrapped C/C++ object of type View1Widget has been deleted