A good solution is to create a custom signal for the child, and emit it when the window is closed.
Note that in order to do that, you have to correctly use pyuic generated files, which is not what you're doing: those files should never, ever be manually modified, as they are only meant for imports and are not intended for further implementation: there are lots of reasons for not doing that, and one of them is that their structure might lead to confusion about the object structure. You can read more about the correct usage of those files in the official PyQt guidelines about using Designer.
Most importantly, since those are simple python object
classes (and not Qt widget classes), they don't allow method overriding, which is very important especially in cases like this one.
So, before going on with the example, rebuild those files with pyuic
and create a new script for your program.
The concept is that the child class will have a closed
signal, and the signal will be emitted within the closeEvent
(which is called everytime the window is closed by the user or programmatically with close()
); then main window creates the child (but doesn't show it) right in the __init__
, and connects its custom signal with that window's show
.
from PyQt5 import QtCore, QtGui, QtWidgets
from test_parent import Ui_MainWindow
from test_child import Ui_child
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.openChild)
# create an instance of the child
self.child = Child()
# connect its closed signal to show() of this window
self.child.closed.connect(self.show)
def openChild(self):
self.child.show()
self.hide()
class Child(QtWidgets.QMainWindow, Ui_child):
closed = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
self.setupUi(self)
def closeEvent(self, event):
self.closed.emit()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…