我想在主窗口关闭时关闭主窗口打开的所有其他窗口。
请在下面找到最小值。我正在测试的代码:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
import sys
class AnotherWindow(QWidget):
"""
This "window" is a QWidget. If it has no parent, it
will appear as a free-floating window as we want.
"""
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)
def show_new_window(self, checked):
self.w = AnotherWindow()
self.w.show()
def close_another_window(self):
if self.w:
self.w.close()
app = QApplication(sys.argv)
w = MainWindow()
app.aboutToQuit.connect(w.close_another_window)
w.show()
app.exec()
如上所示,我尝试使用aboutToQuit
的选项QApplication
,但只有当另一个窗口也关闭时才会调用它。
我想在主窗口关闭时自动关闭另一个窗口。
实施closeEvent https://doc.qt.io/qt-5/qwidget.html#closeEvent:
class MainWindow(QMainWindow):
w = None
# ...
def closeEvent(self, event):
if self.w:
self.w.close()
请注意,您还可以使用QApplication.closeAllWindows() https://doc.qt.io/qt-5/qapplication.html#closeAllWindows关闭any顶级窗口,即使没有任何直接引用,但如果这些窗口中的任何一个忽略了closeEvent()
该函数将停止尝试关闭剩余的。
为了避免这种情况,您可以使用循环所有窗口QApplication.topLevelWidgets() https://doc.qt.io/qt-5/qapplication.html#topLevelWidgets;窗口忽略closeEvent
仍然会保持开放,但是all其他的将被关闭:
def closeEvent(self, event):
for window in QApplication.topLevelWidgets():
window.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)