smallB
smallB

Reputation: 17120

Mapping key press event qt

How to detect which key was pressed by an user?
Tried to search web but couldn't find really anything interesting.
Thanks.

Upvotes: 2

Views: 7060

Answers (1)

sam-w
sam-w

Reputation: 7687

If you want to detect keypresses globally (useful for application shortcuts etc), you'll need to make one of your QObjects the eventFilter for the application, by first overloading QObject::eventFilter:

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

    switch(KeyEvent->key())
    {
      case Qt::Key_F1:
        //do something
        break;
      default:
        break;
    }
  }
}

...and then installing that object as the eventFilter for your application:

QObject *KeyPressEater = GetYourEventFilterObject();
QCoreApplication::instance()->installEventFilter(KeyPressEater);

Otherwise, as @Mat says above, just overload QWidget::keyPressEvent. You'll need to setFocusPolicy and actually have focus in order to get the key presses.

Upvotes: 8

Related Questions