You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5如何实现关闭主窗口时同步关闭所有其他打开的子窗口

问题原因

你使用的aboutToQuit信号触发前提是所有窗口都已关闭、应用即将正式退出。默认配置下PyQt会在最后一个窗口关闭后才触发该信号,你关闭主窗口时子窗口还处于存活状态,该信号不会触发,因此绑定的关闭逻辑无法生效。

解决方案

方案1:重写主窗口closeEvent方法(推荐,灵活性高)

该方案无需修改子窗口逻辑,还支持多子窗口场景,你可以自由控制子窗口关闭前的检查逻辑。
修改后的完整代码如下:

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QCloseEvent
import sys


class AnotherWindow(QWidget):
    """
    无父控件的QWidget会作为自由浮动窗口显示
    """
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.label = QLabel("Another Window")
        layout.addWidget(self.label)
        self.setLayout(layout)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.button = QPushButton("Push for Window")
        self.button.clicked.connect(self.show_new_window)
        self.setCentralWidget(self.button)
        # 用列表存储所有打开的子窗口,支持同时打开多个子窗口的场景
        self.child_windows = []

    def show_new_window(self, checked):
        new_window = AnotherWindow()
        new_window.show()
        self.child_windows.append(new_window)

    def closeEvent(self, event: QCloseEvent):
        # 遍历关闭所有存活的子窗口
        for window in self.child_windows:
            if window.isVisible():
                window.close()
        # 确认主窗口关闭事件
        event.accept()


app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec()

方案2:绑定父子对象关系(更简洁)

如果不需要单独管理子窗口的生命周期,可以在创建子窗口时将主窗口设为父对象,同时添加窗口标记确保子窗口仍为独立浮动窗口,主窗口关闭时会自动销毁所有子对象,对应子窗口也会同步关闭。
修改点如下:

  1. 导入Qt常量:
from PyQt5.QtCore import Qt
  1. 修改子窗口的初始化方法,接收父对象参数并设置窗口标记:
class AnotherWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 确保子窗口作为独立浮动窗口显示,不会嵌入父窗口
        self.setWindowFlag(Qt.Window)
        layout = QVBoxLayout()
        self.label = QLabel("Another Window")
        layout.addWidget(self.label)
        self.setLayout(layout)
  1. 打开子窗口时传入主窗口作为父对象:
def show_new_window(self, checked):
    self.w = AnotherWindow(self)
    self.w.show()

内容的提问来源于stack exchange,提问作者tonyjosi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:54:06