Search code examples
c++qtkeypressqt-events

How to check if a key is pressed?


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.


Solution

  • 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.