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

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.

This question is related to c++ qt

The answer is


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);
}

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();
}

You can attach a SLOT to the

void aboutToQuit();

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