1from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
2
3import sys
4
5
6class AnotherWindow(QWidget):
7 """
8 This "window" is a QWidget. If it has no parent, it
9 will appear as a free-floating window as we want.
10 """
11 def __init__(self):
12 super().__init__()
13 layout = QVBoxLayout()
14 self.label = QLabel("Another Window")
15 layout.addWidget(self.label)
16 self.setLayout(layout)
17
18
19class MainWindow(QMainWindow):
20
21 def __init__(self):
22 super().__init__()
23 self.button = QPushButton("Push for Window")
24 self.button.clicked.connect(self.show_new_window)
25 self.setCentralWidget(self.button)
26
27 def show_new_window(self, checked):
28 w = AnotherWindow()
29 w.show()
30
31
32app = QApplication(sys.argv)
33w = MainWindow()
34w.show()
35app.exec_()
36
1from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
2
3import sys
4
5from random import randint
6
7
8class AnotherWindow(QWidget):
9 """
10 This "window" is a QWidget. If it has no parent, it
11 will appear as a free-floating window as we want.
12 """
13 def __init__(self):
14 super().__init__()
15 layout = QVBoxLayout()
16 self.label = QLabel("Another Window % d" % randint(0,100))
17 layout.addWidget(self.label)
18 self.setLayout(layout)
19
20
21class MainWindow(QMainWindow):
22
23 def __init__(self):
24 super().__init__()
25 self.w = None # No external window yet.
26 self.button = QPushButton("Push for Window")
27 self.button.clicked.connect(self.show_new_window)
28 self.setCentralWidget(self.button)
29
30 def show_new_window(self, checked):
31 if self.w is None:
32 self.w = AnotherWindow()
33 self.w.show()
34
35 else:
36 self.w.close() # Close window.
37 self.w = None # Discard reference.
38
39
40app = QApplication(sys.argv)
41w = MainWindow()
42w.show()
43app.exec_()
44