Can't override Qwidget closeEvent



  • Hi I am new to Qt, and I am trying to pop up a dialog box when user click the close button on a qwidget, but I don't know why my closeEvent function did not get called at all.

    I have a class look like this:

    .h file

     class EditorPlugin : public QWidget
    {
    ...
    public:
    virtual void closeEvent(QCloseEvent *event) override;
    ...
    }
    

    .cpp file

    void EditorPlugin::closeEvent(QCloseEvent *event)
    {
        QMessageBox msgBox;
        msgBox.setText("The document has been modified.");
        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
                break;
            case QMessageBox::Discard:
                // Don't Save was clicked
                break;
            case QMessageBox::Cancel:
                // Cancel was clicked
                break;
            default:
                // should never be reached
                break;
        }
    
        event->accept();
    }
    

    Anyone knows what is the problem? Thanks in advance.


  • Lifetime Qt Champion

    Hi,

    Just tested it with a minimal application and it's working as expected.

    Maybe a silly question but are you sure that you are closing an EditorPlugin instance ?

    What close button do you mean ?
    What version of Qt are you using ?
    What platform are you running on ?



  • Thanks for spending time looking into my problem. I really appreciate you helps. I made a mistake. I override the closeEvent in a wrong class.



  • Final note: events should be protected, not public


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.