QMainWindow close () signal is not thrown

To warn before closing a window that inherits from QMainWindow, I redefined it closeEvent, which works fine when I emit close()manually. However, pressing the x button does not cause this; he just comes out.

It emits aboutToQuit()for an application that I can use to β€œrestore” a window after it closes. But I want the warning to precede the initial closure.

I am not sure where the problem is. The window is the top level and there are no running threads. I misunderstood which signal is actually connected to the click of a button ...? This close()is right?

+4
source share
2 answers

In the header of the mainwindow class (closeEvent must be virtual):

public:
    /*!
     * \brief closeEvent
     * \param event
     */
    virtual void closeEvent ( QCloseEvent * event );

Then in cpp

void MainWindow::closeEvent( QCloseEvent *event )
{
    //! Ignore the event by default.. otherwise the window will be closed always.
    event->ignore();

    if(!EntitiesSaverObserver::Instance()->isAllSaved())
    {
        QMessageBox msgBox;
        msgBox.setWindowIcon(QIcon(":/Resources/Icons/warning.png"));
        msgBox.setIconPixmap(QPixmap(":/Resources/Icons/warning.png"));
        QString strToShow = QString("Some Entities has been created or modified...");
        msgBox.setText(strToShow);
        msgBox.setInformativeText("Do you want to save your changes?");
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        int ret = msgBox.exec();

        switch (ret) {
          case QMessageBox::Save:
            {
              // Save was clicked
              qDebug() << "SAVE";
              //! Do your stuff here
              // ....
              event->accept();
              break;
            }
          case QMessageBox::Discard:
            {
                // Don't Save was clicked
                qDebug() << "DISCARD";
                event->accept();
                break;
            }
          case QMessageBox::Cancel:
            {
              // Cancel was clicked
              qDebug() << "CANCEL";
              break;
            }
          default:
              // should never be reached
              break;
        }
    } else {
        event->accept(); // Do not need to save nothing... accept the event and close the app
    }
}

In addition, if you want to place the button on the toolbar as a QAction, you can connect a signal, and then:

void MainWindow::on_actionExit_triggered()
{
    close();
}

This will trigger a close event on your main window. Hope this helps you.

+2
source

just create a signal slot QObject :: connect (yourButton, SIGNAL (clicked ()), this, SLOT (close ()));

-1
source

All Articles