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

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

Asked on December 17, 2018 in Qt.
' data-html="true"> Share
  • Comment(0)
  • Add Comment


  • 3 Answer(s)

    Try this solutions:

    The QMainWindow  can be  override  the 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();
       }
    }
    

    By using  subclassing a QDialog closeEvent will be callend and   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();
        }
    }
    
    Answered on December 17, 2018.
    ' data-html="true"> Share
  • Comment(0)
  • Add Comment

    Use this:

    To override the QWidget::closeEvent(QCloseEvent *event) in class definition and add the code into the function.

    class foo : public QMainWindow
    {
        Q_OBJECT
    private:
        void closeEvent(QCloseEvent *bar);
        // ...
    };
     
     
    void foo::closeEvent(QCloseEvent *bar)
    {
       
          // Do something
          bar->accept();
    }
    
    Answered on December 17, 2018.
    ' data-html="true"> Share
  • Comment(0)
  • Add Comment

    The given simple code is:

    void aboutToQuit();
    
    

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

    Answered on December 17, 2018.
    ' data-html="true"> Share
  • Comment(0)
  • Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.