【发布时间】:2017-12-11 20:52:38
【问题描述】:
我有一个带有多个主窗口的 Qt 应用程序,我想在应用程序即将退出时收到一个信号,而所有窗口都还在运行。
QApplication.aboutToQuit 信号对我不起作用,因为它仅在所有窗口关闭后才会触发。
我看到的所有其他答案都建议实现主窗口的 closeEvent() 函数,但我有多个主窗口,我找不到任何方法来区分 CloseEvents 和普通 closeEvent 之间的区别窗口被关闭以及整个应用程序在QMD+Q 之后关闭或在任务栏中使用单击退出或出于任何原因退出时的关闭事件。
只有在整个应用程序即将退出但在任何窗口关闭之前,我如何才能获得信号?
当我按下 Cmd+Q 或右键退出任务栏图标时会发生什么:
- (此时我想要一个信号)
- 所有窗口都获得一个 closeEvent()
- aboutToQuit() 触发
- 应用退出
我想要的是在任何事情发生之前得到一个信号,并且所有的窗户仍然打开。
编辑:最小示例
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QApplication, QWidget
class Win(QWidget):
def closeEvent(self, event: QCloseEvent):
# implementing a custom closeEvent doesn't help me
# this is called for every normal manual window close and when the application quits
# I only want to run something when the full application gets shut down, not just this window
# can't see any way to differentiate between the two
print("closeEvent", event.type(), event)
return super().closeEvent(event)
if __name__ == '__main__':
app = QApplication([])
app.aboutToQuit.connect(lambda :print("about to quit, this is too late, by now all windows are closed"))
#What I need
# app.beforeQuitSignal.connect(lambda :print("signal that it's gonna quit, before any of the windows are closed"))
#stuff I've tried that didn't work either
app.quit = lambda *args:print("quit, doesnt get called")
app.exit = lambda *args:print("exit, doesnt get called")
app.closeAllWindows = lambda *args:print("closeAllWindows, doesnt get called")
mainwins = []
for i in range(5):
win = Win()
win.setGeometry(100*i,100*i, 400,400), win.show(), win.raise_()
mainwins.append(win)
app.exec_()
【问题讨论】:
-
请提供您的申请的Minimal, complete, verifiable example(不是完整的!)。我建议您为每个
QMainWindow重新实现closeEvent()并从这里发出自定义信号,并在您的QApplication中使用一个插槽,但它可能不适合您。 -
@LoïcG。现在添加了示例,但
closeEvent没有帮助,每次用户关闭窗口时都会调用它,我希望它仅在 Alt F4 等之后整个应用程序退出时运行。 -
@Stitch95 也就是说,您需要一个信号,在所有窗口关闭之前提醒您,并告诉您最后一个窗口是否关闭。
-
@eyllanesc 是的,我只想要一个 aboutToQuit 信号,但在任何窗口实际关闭之前。我不在乎最后一个窗口之前是如何关闭的,我只是在示例中添加了 closeEvent ,因为这是建议的解决方案,所以我想说明为什么它不适合我想要的方式
-
您不能将
QApplication.quitOnLastWindowClosed设置为False,以便在最后一个窗口关闭后不立即退出并在退出应用程序之前执行您想做的事情吗?