Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to detect whether a key sequence is pressed and want to perform certain task on that event in Qt. Currently I can detect keypresses for certain widgets but how to detect global keypresses. By global I mean that even if the application is minimized or hidden , it should detect key press.

I tried making an eventFilter for the application, by first overloading QObject::eventFilter like this:

bool GlobalEventFilter::eventFilter(QObject *Object, QEvent *Event)
{
  if (Event->type() == QEvent::KeyPress)
  {
    QKeyEvent *KeyEvent = (QKeyEvent*)Event;

    switch(KeyEvent->key())
    {
      case Qt::Key_F1:
        cout<<"F1 press detected"<<endl;
        return true;
      default:
        break;
    }
  }
  return QObject::eventFilter(Object,Event);
}

and then installing that object as the eventFilter for my application:

QApplication a(argc,argv);
a.installEventFilter(new GlobalEventFilter());

and I also tried the doing this:

QCoreApplication::instance()->installEventFilter(new GlobalEventFilter());

In both the cases I am able to detect key presses when my application window is open but it fails when window is minimized or hidden. How to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
641 views
Welcome To Ask or Share your Answers For Others

1 Answer

This feature is not implemented in Qt. You can use Qxt. Qxt is an extension library for Qt providing a suite of cross-platform utility classes to add functionality not readily available in Qt. It has Global Shortcut (hot keys) which detects key presses even if the application is minimized.

After compiling and linking your application to Qxt, you can include QxtGlobalShortcut:

#include <QxtGlobalShortcut>

Example usage:

QxtGlobalShortcut* shortcut = new QxtGlobalShortcut(window);
connect(shortcut, SIGNAL(activated()), window, SLOT(toggleVisibility()));
shortcut->setShortcut(QKeySequence("Ctrl+Shift+F12"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...