经常有人问到如何在一个主窗口中打开一个对话框,然后在确认对话框之后,开启另一个窗口进行后续操作,
要求主窗口和最终的窗口之间都能响应用户操作,也就是非模态窗口。随手写了几行代码,简要示意。
:::python #!/usr/bin/python # -*- coding: utf-8 -*- # Gui (imgui@qq.com) # License: BSD from PyQt4.QtCore import * from PyQt4.QtGui import * import sys class W1(QWidget): def __init__(self, parent=None): super(W1, self).__init__(parent) self.btn = QPushButton('Click1') vb = QVBoxLayout() vb.addWidget(self.btn) self.setLayout(vb) self.btn.clicked.connect(self.fireupWindows2) def fireupWindows2(self): w2 = W2() if w2.exec_(): self.w3 = W3() # 需要通过self实例化为全局变量,不加self的话,一运行就被回收,也就无法显示。 self.w3.show() class W2(QDialog): def __init__(self, parent=None): super(W2, self).__init__(parent) self.btn = QPushButton('Click2') vb = QVBoxLayout() vb.addWidget(self.btn) self.setLayout(vb) self.btn.clicked.connect(self.fireupWindows3) def fireupWindows3(self): self.accept() class W3(QWidget): def __init__(self, parent=None): super(W3, self).__init__(parent) self.resize(300, 300) self.btn = QLabel('The Last Window') vb = QVBoxLayout() vb.addWidget(self.btn) self.setLayout(vb) if __name__ == "__main__": app = QApplication(sys.argv) w = W1() w.show() sys.exit(app.exec_())
oneMainWindow.py
# -*- coding:utf-8 -*-
from PyQt4.QtGui import (QMainWindow, QPushButton, QApplication,
QVBoxLayout, QWidget)
from PyQt4.QtCore import (Qt, QObject, SIGNAL)
import anotherWindow
import sys
class OneWindow(QMainWindow):
def __init__(self):
super(OneWindow, self).__init__()
self.setGeometry(100, 100, 600, 400)
vLayout = QVBoxLayout()
self.button = QPushButton("OK")
vLayout.addWidget(self.button)
widget = QWidget()
widget.setLayout(vLayout)
self.setCentralWidget(widget)
QObject.connect(self.button,SIGNAL("clicked()") , self.anotherWindow)
def anotherWindow(self):
print 'OK'
self.another = anotherWindow.AnotherWindow()
self.another.show() #难道不是用这个show()函数吗?
if __name__ == '__main__':
app = QApplication(sys.argv)
w = OneWindow()
w.show()
app.exec_()
anotherWindow.py
# -*- coding:utf-8 -*-
from PyQt4.QtGui import (QMainWindow)
class AnotherWindow(QMainWindow):
def __init__(self):
super(AnotherWindow, self).__init__()
self.resize(400, 300)
self.setWindowTitle("this is another window")