How to check if a key is pressed?

2.2k views Asked by At

I would like to be able to check if the key is pressed at any time. I imagine such a solution:

void MyQQuickPaintedItem::keyPressEvent(QKeyEvent * event)
{
  isKeyPressed[ event->key() ] = 1;
}
    
void MyQQuickPaintedItem::keyReleaseEvent(QKeyEvent *event)
{
  isKeyPressed[ event->key() ] = 0;
}

To check if the right arrow key is pressed, it would be enough to check isKeyPressed[ Qt::Key_Right ] value.

I implemented it and it doesn't work. I don't mean that the program crashes. isKeyPressed[ Qt::Key_Right ] is just always 0, even if I'm pressing this right arrow key or any other key.

One of the header files:

...
bool isKeyPressed[255];
...

One of linked files:

...
extern bool isKeyPressed[255];
...

I don't know exactly how big isKeyPressed should be, but I don't get SIGSEGV, so the size is probably ok.

2

There are 2 answers

0
yomol777 On BEST ANSWER

Instead of an array you can use a map, if you are not interested in the order, then you can use unordered_maps which is faster. There are rather few keys, so I think the program will run fast anyway.

0
ΦXocę 웃 Пepeúpa ツ On

You normally don't address the problem like that, at least not using Qt.

If you want to "catch" some key pressed events, then Qt offers ways to do that.

What you can do is connect the shortcut to a lambda or a slot, and in there, do what ever you need, like for e.g., catching when the user presses Ctrl + I:

connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_I), this), &QShortcut::activated, [](){qDebug() << "Here we are!";});