13

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?

NG_
  • 6,895
  • 7
  • 45
  • 67
Mohammad Sheykholeslam
  • 1,379
  • 5
  • 18
  • 35

3 Answers3

29

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.

Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
6

The code below prevents a dialog close when pressed Alt+F4, [X] or Escape, but not by calling SomeDialog::close() method.

void SomeDialog::closeEvent(QCloseEvent *evt) {
    evt->setAccepted( !evt->spontaneous() );
}   

void SomeDialog::keyPressEvent(QKeyEvent *evt) {
    // must be overridden but empty if the only you need is to prevent closing by Escape
}   

good luck to all of us ;)

  • You have got two errors: it is `keyPressEvent(QKeyEvent *evt)` `Press` not `Pressed` and the type is different. But with this fix applied... it works well. :) – HiFile.app - best file manager Jan 12 '17 at 20:03
  • Just overriding keyPressEvent(QKeyEvent *evt) and leaving it empty, might cause other problems, such as not working Enter key behavior which might be needed, for instance, when we want to allow the user to continue by clicking Enter key. So, it is much better to define keys we don't want to allow explicitly in such specific cases. Or, in other words, it would be advisable to call BaseWidget::keyPressEvent(evt) where BaseWidget is something that is inherited (it could be QWidget, QDialog, etc.) – Vaidotas Strazdas Aug 29 '17 at 14:25
1

Also you can handle the event in your dialog's class (at least if it's modal dlg):

void MyDialog::closeEvent(QCloseEvent* e)
{
    if ( condition )
       e->ignore();
    else
       __super::closeEvent(e);
}
Illia Levandovskyi
  • 1,228
  • 1
  • 11
  • 20