有两个 .py 文件放在同一个文件夹中:
dialog_01.py and dialog_02.py
两个文件互为副本。两者都构建了一个带有两个按钮的简单 QMainWindow 对话框窗口:“确定”和“取消”。
单击“确定”按钮关闭当前打开的对话窗口并打开另一个。因此,如果单击 Dialog_01 的确定按钮,将关闭 dialog_01 并打开 dialog_02。如果单击 Dialog_02 的确定按钮,则关闭 dialog_02 并打开 dialog_01,依此类推。
编辑问题:
关闭对话框会使 Python 进程仍在后台运行(可以在 OSX 事件监视器或 Windows 任务管理器中看到)。
如何确保对话窗口关闭后Python进程终止?
dialog_01.py
import sys, os
from PyQt4 import QtCore, QtGui
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
Cancel_button = QtGui.QPushButton("Cancel")
Cancel_button.clicked.connect(self.Cancel)
myBoxLayout.addWidget(Cancel_button)
Button_01 = QtGui.QPushButton("Press to close this dialog and open Dialog 02")
Button_01.clicked.connect(self.callAnotherQMainWindow)
myBoxLayout.addWidget(Button_01)
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.setWindowTitle('Dialog 01')
def callAnotherQMainWindow(self):
from dialog_02 import Dialog_02
self.close()
self.dialog_02 = Dialog_02()
self.dialog_02.show()
self.dialog_02.raise_()
def Cancel(self):
self.close()
def closeEvent(self):
self.deleteLater()
if __name__ == '__main__':
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
dialog_02.py
import sys, os
from PyQt4 import QtCore, QtGui
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
class Dialog_02(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
Cancel_button = QtGui.QPushButton("Cancel")
Cancel_button.clicked.connect(self.Cancel)
myBoxLayout.addWidget(Cancel_button)
Button_02 = QtGui.QPushButton("Press to close this dialog 02 and re-open Dialog 01")
Button_02.clicked.connect(self.callAnotherQMainWindow)
myBoxLayout.addWidget(Button_02)
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.setWindowTitle('Dialog 02')
def callAnotherQMainWindow(self):
from dialog_01 import Dialog_01
self.close()
self.dialog_01 = Dialog_01()
self.dialog_01.show()
self.dialog_01.raise_()
def Cancel(self):
self.close()
def closeEvent(self):
self.deleteLater()
if __name__ == '__main__':
dialog_2 = Dialog_02()
dialog_2.show()
dialog_2.resize(480,320)
sys.exit(app.exec_())
请您参考如下方法:
重写 QtGui.QMainWindow 类的 closeEvent() 函数,如下所示:
def closeEvent(self, event):
self.deleteLater()
这似乎有效:
删除这个:
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
还有这个:
if __name__ == '__main__':
dialog_2 = Dialog_02()
dialog_2.show()
dialog_2.resize(480,320)
sys.exit(app.exec_())
...来自 dialog2 文件的技巧。
