我有一个具有多个主窗口的Qt应用程序,希望在所有窗口仍然打开时获取一个应用程序即将退出的信号。因为
QApplication.aboutToQuit
信号只会在所有窗口关闭后才会被触发,所以该信号对我来说不可用。我看到的所有其他答案都建议实现主窗口的closeEvent()
函数,但是我有多个主窗口,并且我找不到任何区分正常单个窗口关闭的CloseEvent
和整个应用程序关闭的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_()
QMainWindow
重新实现closeEvent()
,并从此处发出自定义信号,并在您的QApplication
中使用一个槽,但也许这对您来说不太合适。 - Loïc G.closeEvent
并没有帮助,因为它每次用户关闭窗口时都会被调用,我希望它只在整个应用程序在按下 Alt F4 等键后退出时运行。 - Stitch95QApplication.quitOnLastWindowClosed
设置为 False,以便在最后一个窗口关闭后不立即退出,并在退出应用程序之前执行想要的操作吗? - Loïc G.