Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dialog closeEvent is never called



  • I have a Dialog which overrides closeEvent because on close i want to safe some settints. However it is never called the close Event.

    #ifndef WINDIALOG_H
    #define WINDIALOG_H
    
    #include "gamesettings.h"
    
    #include <QDialog>
    
    namespace Ui {
    class WinDialog;
    }
    
    class WinDialog : public QDialog
    {
        Q_OBJECT
    public:
        WinDialog(int recordTime, QWidget *parent = nullptr);
        ~WinDialog() override;
    
    protected:
        void closeEvent(QCloseEvent *event) override;
    
    private:
        GameSettings mGameSettings;
        int mRecordTime;
        Ui::WinDialog *ui;   
    };
    
    #endif // WINDIALOG_H
    
    void WinDialog::closeEvent(QCloseEvent *event)
    {
        Q_UNUSED(event)
    
        switch(mGameSettings.difficulty()){
        case GameSettings::Difficulty::beginner:
            mGameSettings.setBeginnerTime(mRecordTime);
            mGameSettings.setBeginnerName(ui->playerNameLineEdit->text());
            break;
        case GameSettings::Difficulty::intermediate:
            mGameSettings.setIntermediateTime(mRecordTime);
            mGameSettings.setIntermediateName(ui->playerNameLineEdit->text());
            break;
        case GameSettings::Difficulty::expert:
            mGameSettings.setExpertTime(mRecordTime);
            mGameSettings.setExpertName(ui->playerNameLineEdit->text());
            break;
        case GameSettings::Difficulty::custom:
            break;
        }
    }
    

    The Dialog is called inside a class derived from QWidget like this:

            auto dialog = new WinDialog{ recordTime, this };
            dialog->setAttribute(Qt::WA_DeleteOnClose);
    
            dialog->show();
            dialog->exec();
    

    I thought closeEvent allways gets called?



  • Why are you calling show() and exec() ? It should be one or the other depending on whether you are modal or not.


  • Moderators

    Close event happens when you hit the close button. You can connect to the finished() signal instead.

    As @mranger90 said show() is called by exec() so that's not needed. Also don't forget to check the return value of exec() and, since exec() is blocking anyway, it's more idiomatic to create the dialog on the stack instead of heap + WA_DeleteOnClose.



  • This post is deleted!

Log in to reply