26

I'd like to do some house keeping stuff (like writing to a file etc) in a Qt app before the app exits. How can I get to this function (exit or whatever is called) in Qt?

Bart
  • 19,692
  • 7
  • 68
  • 77
smallB
  • 16,662
  • 33
  • 107
  • 151

2 Answers2

39

You need to connect a slot with the clean up code to the QCoreApplication::aboutToQuit() signal.

This allows you to delete QObjects with QObject::deleteLater() and the objects will be deleted as you have not yet left the main application event loop.

If you are using a C library that requires a 'shutdown' call you can normally do that after the return from QCoreApplication::exec().

Example for both techniques:

int main(int,char**)
{
  QApplication app;
  library_init();
  QWidget window;
  window.show();
  QObject::connect(&app, SIGNAL(aboutToQuit()), &window, SLOT(closing()));
  const int retval = app.exec();
  library_close();
  return retval;
}
Silas Parker
  • 8,017
  • 1
  • 28
  • 43
  • 4
    Note that current Qt documentation specifically recommends against doing anything after exec returns. See (http://doc.qt.io/qt-5/qapplication.html#exec) – Steve Fallows Mar 05 '15 at 22:42
  • 1
    Note that a reboot from terminal or a lost X connection triggers a ::exit() which does not emit aboutToQuit. (at least until 5.7) – ManuelSchneid3r Oct 13 '16 at 15:01
10

In regards to Silas Parker's answer, the Qt documentation says this about the aboutToQuit signal:

The signal is particularly useful if your application has to do some last-second cleanup. Note that no user interaction is possible in this state.

If you want your application to be able to cancel the exiting process or allow the user to perform a last minute change before the application closes, then you can do this by handling the closeEvent function in your MainWindow.

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

See the closeEvent documentation for more information.

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • How can this be handled in QApplication instead of QMainWIndow? – prakashpun Jul 07 '15 at 05:43
  • 1
    @pra16 `QApplication` doesn't really have a corollary to `closeEvent`. You could try using [`lastWindowClosed`](http://doc.qt.io/qt-5/qguiapplication.html#lastWindowClosed) or use signal handling to interrupt the suspend/close signals. – Cory Klein Jul 13 '15 at 23:21