Table of Contents

Quitting

There are a few ways to terminate a Qt app and so you might wonder what the BlessedHolyWay is. I'm not sure that I've figured that out, but for now I will document the different ways that are available of which I am aware.

QApplication::lastWindowClosed()

From the Qt help files:

void QApplication::lastWindowClosed () [signal]

This signal is emitted from QApplication::exec() when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed.

By default,

So, one way to quit your app is to direct an event or action handler to the slot

bool QWidget::close ()

on your main window, e.g.:

void MainWindow::on_button_quit_event_clicked()
{
    this->close();
}

or (in MainWindow's constructor)

connect(widget.button_quit, SIGNAL(clicked()), this, SLOT(close()));

QCoreApplication::exit ( returnCode )

From the Qt help files:

void QCoreApplication::exit ( int returnCode = 0 ) [static]

Tells the application to exit with a return code.

After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns returnCode. If the event loop is not running, this function does nothing.

By convention, a returnCode of 0 means success, and any non-zero value indicates an error. Note that unlike the C library function of the same name, this function does return to the caller – it is event processing that stops.2)

So, you might,

void MainWindow::on_actionE_xit_triggered()
{
    qApp->exit();
}

or (in MainWindow's constructor)

connect(widget.button_exit_fail, SIGNAL(clicked()), &app, SLOT(exit(1)));

QCoreApplication::quit ()

From the Qt help files:

void QCoreApplication::quit () [static slot]

Tells the application to exit with return code 0 (success). Equivalent to calling QCoreApplication::exit(0).

It's common to connect the QApplication::lastWindowClosed() signal to quit(), and you also often connect e.g. QAbstractButton::clicked() or signals in QAction, QMenu, or QMenuBar to it.

Example:

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, SIGNAL(clicked()), &app, SLOT(quit()));

3)