参考:
https://blog.csdn.net/wq_ocean_/article/details/129475276
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建主页面中的按钮
self.button = QPushButton('打开新页面', self)
self.button.move(50, 50)
self.button.clicked.connect(self.open_new_window)
# 标记新页面是否存在
self.new_window_exists = False
def open_new_window(self):
# 创建新页面
self.new_window = NewWindow(self)
self.new_window_exists = True
self.new_window.show()
def closeEvent(self, event):
# 如果新页面存在,禁止关闭主页面
if self.new_window_exists:
event.ignore()
else:
event.accept()
class NewWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# 设置新页面中的窗口大小和标题
self.setGeometry(100, 100, 300, 200)
self.setWindowTitle('新页面')
# 在新页面中添加标签显示其他内容
self.label = QLabel('这是新页面中的内容', self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setGeometry(50, 50, 200, 100)
def closeEvent(self, event):
# 标记新页面不存在并关闭新页面
self.parent().new_window_exists = False
self.parent().show()
event.accept()
if __name__ == '__main__':
app = QApplication([])
main_window = MainWindow()
main_window.show()
app.exec_()