Pass Parent to Child Window in PyQt5 Mar 13th 2021 Words: 160

Here is an example of spawning a child window in the main window. The child window will be automatically destroyed on main window close.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QStatusBar, QDialog, QMenuBar


class MainWindow(QMainWindow):

def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My Fancy App")

# Toolbar
menu_bar = QMenuBar()

self.window_about = AboutWindow(self) # pass MainWindow instance as parent of AboutWindow
button_action_about = QAction("About", self)
button_action_about.setStatusTip("About this application")
button_action_about.triggered.connect(self.on_button_action_about_click)
menu_bar.addAction(button_action_about)

self.setMenuBar(menu_bar)

# Status bar
self.setStatusBar(QStatusBar(self))

def on_button_action_about_click(self):
self.window_about.show()


class AboutWindow(QDialog):
def __init__(self, *args, **kwargs):
super(AboutWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("About")


if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

Note the AboutWindow class in the child of QDialog, inherit from QWdget does not work. I dunno why though.