PyQt多窗口调用
经常有人问到如何在一个主窗口中打开一个对话框,然后在确认对话框之后,开启另一个窗口进行后续操作,
要求主窗口和最终的窗口之间都能响应用户操作,也就是非模态窗口。随手写了几行代码,简要示意。
:::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_())