How can I disable Alt + F4 window closing using Qt?

Mohammad Sheykholeslam picture Mohammad Sheykholeslam · Apr 29, 2012 · Viewed 13.6k times · Source

I've disabled X button in Qt from my dialog using this line:

myDialog->setWindowFlags(Qt::Dialog | Qt::Desktop)

but I couldn't detect Alt + F4 using this code:

void myClass::keyPressEvent(QKeyEvent *e)
{
    if ((e->key()==Qt::Key_F4) && (e->modifiers()==Qt::AltModifier))
        doSomething();
}

what should I do to detect Alt+F4 or disable it in Qt?

Answer

Arnold Spence picture Arnold Spence · Apr 29, 2012

Pressing Alt+F4 results in a close event being sent to your top level window. In your window class, you can override closeEvent() to ignore it and prevent your application from closing.

void MainWindow::closeEvent(QCloseEvent * event)
{
    event->ignore();
}

If you left the close button (X) visible, this method would also disable it from closing your app.

This is usually used to give the application a chance to decide if it wants to close or not or ask the user by displaying an "Are you sure?" message box.