QMainWindow 和QWidget相互控制
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Main Window')
self.setGeometry(100, 100, 600, 400)
self.label = QLabel("Main Window", self)
self.setCentralWidget(self.label)
self.close_button = QPushButton("Close and Show QWidget", self)
self.close_button.clicked.connect(self.close_and_show_widget)
self.setCentralWidget(self.close_button)
def closeEvent(self, event):
print("QMainWindow closeEvent triggered")
event.accept() # Accept the close event
def close_and_show_widget(self):
self.close()
self.widget = MyWidget(self)
self.widget.show()
def __del__(self):
print("QMainWindow is being destroyed")
class MyWidget(QWidget):
def __init__(self, main_window):
super().__init__()
self.main_window = main_window
self.setWindowTitle('New Widget')
self.setGeometry(150, 150, 300, 200)
layout = QVBoxLayout()
label = QLabel("This is a new QWidget", self)
layout.addWidget(label)
self.return_button = QPushButton("Return to Main Window", self)
self.return_button.clicked.connect(self.return_to_main_window)
layout.addWidget(self.return_button)
self.setLayout(layout)
def return_to_main_window(self):
self.close()
self.main_window.show()
app = QApplication(sys.argv)
mainWin = MyMainWindow()
mainWin.show()
sys.exit(app.exec_())