QT How to check if key is pressed?

Viewed 1232

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 program crashes. isKeyPressed[ Qt::Key_Right ] is just always 0, even if I'm pressing this right arrow key or any other key.

EDIT:

One of 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 Answers

you normally dont address the problem like that... at least not using QT...

if you are interested 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 inside there do what ever you need... like e.g. catching when the user press "control + i"

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

Instead of an array you can use the 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.

Related