Important: Please read the Qt Code of Conduct -

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
    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);
        int ret = msgBox.exec();
        switch (ret) {
            case QMessageBox::Save:
                // Save was clicked
            case QMessageBox::Discard:
                // Don't Save was clicked
            case QMessageBox::Cancel:
                // Cancel was clicked
                // should never be reached

    Anyone knows what is the problem? Thanks in advance.

  • Lifetime Qt Champion


    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