Qt: How do I handle the event of the user pressing the 'X' (close) button?

C++Qt

C++ Problem Overview


I am developing an application using Qt. I don't know which slot corresponds to the event of "the user clicking the 'X'(close) button of the window frame" i.e. this button:

Close button of the window

If there isn't a slot for this, can anyone suggest me some other method by which I can start a function after the user presses that close button.

C++ Solutions


Solution 1 - C++

If you have a QMainWindow you can override closeEvent method.

#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                tr("Are you sure?\n"),
                                                                QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::Yes);
    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}


If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

void MyDialog::reject()
{
    QMessageBox::StandardButton resBtn = QMessageBox::Yes;
    if (changes) {
        resBtn = QMessageBox::question( this, APP_NAME,
                                        tr("Are you sure?\n"),
                                        QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                        QMessageBox::Yes);
    }
    if (resBtn == QMessageBox::Yes) {
        QDialog::reject();
    }
}

Solution 2 - C++

Well, I got it. One way is to override the QWidget::closeEvent(QCloseEvent *event) method in your class definition and add your code into that function. Example:

class foo : public QMainWindow
{
    Q_OBJECT
private:
    void closeEvent(QCloseEvent *bar);
    // ...
};


void foo::closeEvent(QCloseEvent *bar)
{
    // Do something
    bar->accept();
}

Solution 3 - C++

You can attach a SLOT to the

void aboutToQuit();

signal of your QApplication. This signal should be raised just before app closes.

Solution 4 - C++

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
	// do what you need here
    // then call parent's procedure
	QWidget::closeEvent(event);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShravanView Question on Stackoverflow
Solution 1 - C++asclepixView Answer on Stackoverflow
Solution 2 - C++ShravanView Answer on Stackoverflow
Solution 3 - C++Sebastian LangeView Answer on Stackoverflow
Solution 4 - C++AlexanderView Answer on Stackoverflow