如何在退出时调用一个插槽

How to call a slot on quit

本文关键字:一个 插槽 调用 退出      更新时间:2023-10-16

我想在Qt应用程序关闭之前更新我的数据库。

我想要像connect(this, SIGNAL(quit()), this, SLOT(updateDatabase()))这样的东西一种方法是引入退出按钮,但是如果用户按下Alt+F4,是否可以实现此功能呢?

aboutToQuit()信号代替

这个信号在应用程序即将退出主进程时发出事件循环,例如当事件循环级别降为零时。这可能发生在从应用程序内部调用quit()之后或当用户关闭整个桌面会话时。

如果应用程序必须执行某些操作,则该信号特别有用最后的清理工作。注意,这里不允许用户交互状态。

例如:

connect(this, SIGNAL(aboutToQuit()), this, SLOT(updateDatabase()));

还有另一种方法,不是aboutToQuit()信号,而是重新实现 closeEvent(QCloseEvent *event)。可以在语句event->accept();

之前调用slot

:

void MainWindow::closeEvent(QCloseEvent *event)
{
    call_your_slot_here();
    // accept close event
    event->accept();
}