Search code examples
pythonpython-3.xpyqtpyqt5mdichild

Mdi sub window close


I would like to close the MDI subwindow with a push of a button within the window instead of closing it with the x at the top. I have another file with a few classes that has all of the information about the window that is opening up in the MDI area. I have tried self.close() but that leaves the window open and clears all of the widgets from the window. I will post the code below for how I am adding the subwindow to the MDI area.

subWindow = QtWidgets.QMdiSubWindow()
New_Window = NewMDIWindow()
subWindow.setWidget(New_Window)
subWindow.setObjectName("New_Window")
subWindow.setWindowTitle("New SubWindow")
self.MainUi.mdiArea.addSubWindow(subWindow )

subWindow.show()

Solution

  • The X button closes the QMdiSubWindow, not the widget inscribed on it, so the button should close the subwindow:

    your_QPushButton.clicked.connect(your_QMdiSubWindow.close)
    

    Complete Example:

    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            QtWidgets.QMainWindow.__init__(self, parent)
            self.centralwidget = QtWidgets.QWidget(self)
            self.setCentralWidget(self.centralwidget)
            self.centralwidget.setLayout(QtWidgets.QVBoxLayout(self.centralwidget))
    
            self.mdiArea = QtWidgets.QMdiArea(self.centralwidget)
            self.centralwidget.layout().addWidget(self.mdiArea)
    
            subWindow = QtWidgets.QMdiSubWindow(self)
    
            widget = QtWidgets.QWidget()
            widget.setLayout(QtWidgets.QVBoxLayout())
            btn = QtWidgets.QPushButton("close", widget) 
            widget.layout().addWidget(btn)
    
            btn.clicked.connect(subWindow.close)
    
            subWindow.setWidget(widget)
            subWindow.setObjectName("New_Window")
            subWindow.setWindowTitle("New SubWindow")
            self.mdiArea.addSubWindow(subWindow)
    
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())