I'm quite new to pyqt. I want to close the other windows (secondary windows) automatically when the main window is closed in pyqt5. Following up this question, the closeEvent
method was not able to close the secondary windows in the case of the below min. reproducible code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QLabel, QVBoxLayout, QWidget
class AnotherWindow(QWidget):
"""
This "window" is a QWidget. If it has no parent, it
will appear as a free-floating window as we want.
"""
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.label = QLabel("Another Window")
layout.addWidget(self.label)
self.setLayout(layout)
class Ui_MainWindow(QtCore.QObject):
def __init__(self):
super(Ui_MainWindow, self).__init__()
self.w = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(222, 169)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.pbConnect = QtWidgets.QPushButton(self.groupBox_2)
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_2)
self.gridLayout_2.setObjectName("gridLayout_2")
self.pbConnect.setFocusPolicy(QtCore.Qt.StrongFocus)
self.pbConnect.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.pbConnect.setDefault(False)
self.pbConnect.setObjectName("pbConnect")
self.gridLayout_2.addWidget(self.pbConnect, 2, 0, 1, 1)
self.retranslateUi(MainWindow)
def callControl(self):
self.pbConnect.clicked.connect(self.pbConnect_clicked)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
self.pbConnect.setText(_translate("MainWindow", "Connect Device"))
def pbConnect_clicked(self):
self.w = AnotherWindow()
self.w.show()
def closeEvent(self, event):
if self.w:
self.w.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('icon.png'))
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.callControl()
MainWindow.show()
sys.exit(app.exec_())
What am I missing here.
Thanks