Nominate our 2022 Qt Champions!

[solved] QDialog closing

  • Hi everybody,
    my problem is that when I click on the OK button on the QDialogButtonBox of my dialog, I have to verify data inserted in the dialog and if there's something wrong, show a messagebox and avoid closing the dialog.
    now I'm handling the accept() slot, and it seems it's impossible to stop closing when clicked on the button.
    Is there a way to avoid window closing?

  • Probably you should re-write "QDialog::closeEvent": and ignore this event if you wish.

  • You can override closeEvent and add your additional test code before accept the closing.

    @void MyDialog::closeEvent(QCloseEvent *event) {
    if (maybeSave()) {
    event->accept(); // close window
    } else {
    event->ignore(); // keep window

  • if you use QPushButton, than you can connect signal to you slot, and then do validation, if your data is valid, then exec QDialog::accept() slot, else - do nothing :)

  • or if you use QDialogButtonBox you can do like that:
    @switch (m_ui.btnBox->buttonRole(btnClicked)){
    case QDialogButtonBox::ResetRole:
    case QDialogButtonBox::AcceptRole:
    if (isValid()) {
    s_rows = m_rows;
    case QDialogButtonBox::RejectRole:

  • Another approach is ot validate the input data as it changes and only enable the OK button when the data is valid.

  • thanks a lot everybody. I've decided to follow Maxim advice.
    close event is also raised when the user closes the window with the X or via the window manager, and in this case I don't want to save anything.
    bye bye

Log in to reply