How can I catch Alt+F4 in my Qt application ?

Alt+F4 is a key combination controlled by Windows and Qt has no control over such system keys. What you can try to get around this is to start a QTimer to calculate the time from when Alt is pressed until the widget receives a closeEvent() [doc.qt.nokia.com]. If the closeEvent() [doc.qt.nokia.com] is received before e.g 300 msecs have passed, you can assume that Alt+F4 was pressed. See the following example for an illustration:

  1. #include <QtGui>
  2.  
  3. class MainWindow : public QMainWindow
  4. {
  5.         Q_OBJECT
  6. public:
  7.         MainWindow() : QMainWindow()
  8.         {
  9.                 altPressed = false;
  10.                 installEventFilter(this);
  11.         }
  12.        
  13.         void closeEvent(QCloseEvent *event)
  14.         {
  15.                 if (altPressed) {
  16.                         qDebug() << "Alt + f4 was pressed, causing shutdown";
  17.                 } else {
  18.                         qDebug() << "Alt + f4 was not pressed. Shutting down for another reason";
  19.                 }
  20.                 QMainWindow::closeEvent(event);
  21.          }
  22.         bool eventFilter(QObject *o, QEvent *e)
  23.         {
  24.                 if (e->type() == QEvent::ShortcutOverride) {
  25.                         QKeyEvent *event = (QKeyEvent *)e;
  26.                         if(event->modifiers() == Qt::AltModifier) {
  27.                                 altPressed = true;
  28.                                 QTimer::singleShot(300, this, SLOT(testSlot()));
  29.                                 return false;
  30.                         }
  31.                 }
  32.                 return QMainWindow::event(e);
  33.         }
  34.         public slots:
  35.                 void testSlot()
  36.                 {
  37.                         qDebug() << "Only Alt was pressed";
  38.                         altPressed = false;
  39.                 }
  40. private:
  41.         bool altPressed;
  42.  
  43. };
  44. #include "main.moc"
  45. int main(int argc, char **argv)
  46. {
  47.         QApplication app(argc, argv);
  48.         MainWindow main;
  49.         main.show();
  50.         return app.exec();
  51. }

2 comments

December 5, 2010

Picture of xsacha xsacha

Ant Farmer

That’s cool.

But why is it 300msec? Any reasoning behind this?

April 20, 2011

Picture of sigrid sigrid

Hobby Entomologist

300 msec is just used as an example value. In this example we assume that it is unlikely that the user/system will have triggered a close event in a different way if we receive a close event 300 ms after Alt was pressed. This is just a suggested value though, it can of course be replaced by a value you find more suitable

Write a comment

Sorry, you must be logged in to post a comment.