QT How to check if key is pressed? - c++

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.

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

How to avoid handling both the key-event and char-event

To handle text input I've set up a char-event callback with glfwSetCharCallback, and to handle non-text keypresses (arrow keys & hotkeys) I've set up a key-event callback with glfwSetKeyCallback.
What happens in this situation is that for a key press of a character key, I get two calls, one in the key-event callback, and then one in the char-event callback. This can cause unwanted effects - for example let's suppose the user configured the key "a" to enter "Append Mode" of a text editor - after it enters the mode it will also enter the character "a".. Is there a good way to handle this?
So far I've relied on both events arriving together before glfwPollEvents returns, and have merged them. But I get reports that this scheme doesn't work well on some Ubuntu systems..
I've been having trouble with this one as well. After some rudimentary debugging I found that if you press, hold then release a 'typable' key (meaning a key which may fire both the glfwKeyCallback and glfwCharCallback), the output is as follows:
KeyCallback - pressed
CharCallback - typed
KeyCallback - repeated
CharCallback - typed
(3. and 4. repeat until key is released)
KeyCallback - released
With this, and judging from the fact that there is a 0ms delay between the two events firing, they're probably fired sequentially. The solution I came up with (is rather janky), and involves creating some sort of KeyEvent structure:
(examples are in C++)
enum KeyEventType
{
Pressed,
Repeated,
Released
}
struct KeyEvent
{
KeyEventType Type;
int Key;
unsigned char Codepoint;
bool IsTyped;
}
and store it along with an index variable, such as
[main/input class]
std::vector<KeyEvent> m_KeyEvents;
size_t m_LastKeyEventIndex;
in the main file.
Then, when the glfwKeyCallback fires, push a new KeyEvent into the vector:
[glfwKeyCallback]
KeyEventType type = (action == GLFW_PRESS ? KeyEventType::Pressed : (action == GLFW_REPEAT ? KeyEventType::Repeated : KeyEventType::Released));
KeyEvent event = KeyEvent(type, key);
m_KeyEvents.push_back(event);
m_LastKeyEventIndex = m_KeyEvents.size() - 1;
and if the glfwCharCallback fires, we know from the debugging that it should be (immediately) after the corresponding keyCallback event, so you can modify the last added entry in the vector to add the codepoint and mark it as a 'typed' event, after-the-fact. This also gives the added benefit of tying the actual key that was pressed to the generated codepoint, which could come in useful.
[glfwCharCallback]
m_KeyEvents.at(m_LastKeyEventIndex).Codepoint = codepoint;
m_KeyEvents.at(m_LastKeyEventIndex).IsTyped = true;
Finally, in the main loop when you go to call glfwPollEvents(), process all those pending KeyEvents and then clear the vector and reset the index.
I haven't fully tested this yet, but some very rudimentary debugging shows this as a promising solution, resulting in the following*:
*I'm using a custom Key enum in place of the int Key. You could probably use glfwGetKeyName() to get the printable key name, however this resulted in exceptions for me when pressing some keys.

QKeyEvent isAutoRepeat not working?

So, I have an application where if a particular button is kept pressed it plays an audio device, when the button is released it stops the audio device. I use keyPressEvent and KeyReleaseEvent to implement this which is similar to the code below:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 pressed"<<endl;
}
else
{
QWidget::keyPressEvent(event);
}
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 released"<<endl;
}
else
{
QWidget::keyReleaseEvent(event);
}
}
}
But apparently isAutoRepeat function isn't working as I can see continuous print out of key_0 pressed and key_0 released despite the fact I haven't released the 0 key after I have pressed it. Is my code wrong or something else is wrong?
Thanks.
EDIT
I think this is happening because the MainWindow loses the keyboard focus. How can I actually find out which widget has the focus? I'm actually using some widgets when Qt::Key_0 pressed, but I thought I set all those possible widgets to Qt::NoFocus, I guess it's not working.
I'm trying to know which widget has the focus by doing the following:
QWidget * wigdet = QApplication::activeWindow();
qDebug()<<wigdet->accessibleName()<<endl;
but it always prints an empty string. How can I make it print the name of the widget which has the keyboard focus?
So as I also stumbled over this issue (and grabKeyboard didn't really help), I begun digging in qtbase. It is connected to X11 via xcb, and by default, in case of repeated keys, X11 sends for each repeated key a release-event immediately followed by a key-press-event. So holding down a key results in a sequence of XCB_BUTTON_RELEASE/XCB_BUTTON_PRESS-events beeing sent to the client (try it out with xev or the source at the end of this page).
Then, qt (qtbase/src/plugins/platforms/xcb/qxcbkeyboard.cpp) tries to figure out from these events whether its an autorepeat case: when a release is received, it uses a lookahead feature to figure if its followed by a press (with timestamps close enough), and if so it assumes autorepeat.
This does not always work, at least not on all platforms. For my case (old and outworn slow laptop (Intel® Celeron(R) CPU N2830 # 2.16GHz × 2) running ubuntu 16.04), it helped to just put a usleep (500) before that check, allowing the press event following the release event to arrive... it's around line 1525 of qxcbkeyboard.cpp:
// look ahead for auto-repeat
KeyChecker checker(source->xcb_window(), code, time, state);
usleep(500); // Added, 100 is to small, 200 is ok (for me)
xcb_generic_event_t *event = connection()->checkEvent(checker);
if (event) {
...
Filed this as QTBUG-57335.
Nb: The behaviour of X can be changed by using
Display *dpy=...;
Bool result;
XkbSetDetectableAutoRepeat (dpy, true, &result);
Then it wont send this release-press-sequences in case of a hold down key, but using it would require more changes to the autorepeat-detection-logic.
Anyway solved it.
The problem was that I have a widget which is a subclass of QGLWidget which I use to show some augmented reality images from Kinect. This widget takes over the keyboard focus whenever a keyboard button is pressed.
To solve this problem, I needed to call grabKeyboard function from the MainWindow class (MainWindow is a subclass of QMainWindow), so this->grabKeyboard() is the line I needed to add when key_0 button is pressed so that MainWindow doesn't lose the keyboard focus, and then when the key is released I needed to add the line this->releaseKeyboard() to resume normal behaviour, that is, other widgets can have the keyboard focus.

How to read key from keyboard in c++?

How to read key from keyboard in c++ ?
i used _getch() but this is not working always.
i heard about win32 keyboard api. i am targeting to windows so window specific technique is fine. can anyone give me simple example how to read key and check for arrow and function key.
i read article
How to simultaneous read keys on keyboard?
but this is not working in may case. here is my attempt inspired from above linked reference
char temp;
BYTE keys[256];
while(true)
{
temp = _getch();
if(GetKeyboardState(keys))
{
if(keys[VK_UP]&0xF0)
{
// Move Up : Case failing when i pressed up key
}
else if(keys[VK_DOWN]&0xF0 || keys[VK_RETURN]&0xF0)
{
// Move Down : Case failing when i pressed down or enter
}
else if(keys[VK_TAB]&0xF0)
{
// Move Next : Case failing when i pressed tab
}
else
{
// Print charecter which read using _getch()
cout<<temp;
}
}
}
i read MSDN article but do not understand what they are doing. i am doing such program first time so please make your example clear and illustrative so i can easly get it. thanks
I don't have a Windows machine at hand to test this out, but I am thinking that the fact that you are using temp = _getch(); before GetKeyboardState(keys) is eating your characters.
there are many library in C++ which handle this type of problem, if you are the choice, I advise you to use QKeySequence and other classes to let useful keyboard management.
If you want to see example, refer you to chromium project, here is an example used to test code of "keyboard driver".
you can either search many example with "filetype" syntax in google search engine (example : filetype:cc GetKeyboardState)...
you need to set correctly the layout before use GetKeyboardState...
Hope this help you.
Regards,
/Mohamed

Qt LEFT CTRL Key Code

In Qt's QKeyEvent I can check whether Ctrl was pressed by checking if ev->key() is Qt::Key_Control. But how can I distinguish between the left and right Ctrl keys?
I also need the same thing for Alt and Shift keys.
There is no way to do this using pure Qt methods, as far as I know.
Depending on your platform, however, you might be able to distinguish between the keys using the QKeyEvent::nativeScanCode() method instead of QKeyEvent::key().
For example, on Windows you should be able to test which Ctrl key was pressed as follows:
if (event->nativeScanCode() == VK_LCONTROL) {
// left control pressed
} else if (event->nativeScanCode() == VK_RCONTROL) {
// right control pressed
}
According to the Qt Namespace Reference, the enum Qt::Key has a different value for Qt::Key_Alt and Qt::Key_AltGr.
However, enum Qt::KeyboardModifier and enum Qt::Modifier don't see the pair of keys as different modifiers.
(note: I would have posted this as a comment but I don't have enough rep. yet)
Left and Right keys are part of virtual key code -> use nativeVirtualKey() to compare with windows VK_* enums instead of nativescancode().
If VK_RCONTROLdoes not work, check your nativeScanCode value of ctrl-right:
std::cout<<keyEvent->nativeScanCode(); and use this value:
int control_right = 285;
if(key->nativeScanCode() == control_right){...

Check if a Key is Down with Qt

I am playing around with some graphics, and I have implemented simple camera movement with the arrow keys. My first approach was to override keyPressEvent to do something like this:
switch(key)
{
case up: MoveCameraForward(step); break;
case left: MoveCameraLeft(step); break;
...
}
This doesn't work as I wish it would. When I press and hold, for example, the forward key, the camera moves forward "step" units, then halts for a while and then continues moving. I am guessing that this is how the event is generated, in order to avoid multiple events in case of a little bit long keypress.
So, I need to poll the keyboard in my Paint() routine. I haven't found how to do it with Qt. I thought of having a map<Key, bool> which would be updated in keyPressEvent and keyReleaseEvent and poll that map in Paint(). Any better ideas? Thanks for any insights.
This doesn't solve the general problem of detecting which keys are pressed, but if you are only looking for keyboard modifiers (shift, ctrl, alt, etc.), you can retrieve that through the static QApplication::keyboardModifiers() and QApplication::queryKeyboardModifiers() methods.
So, I need to poll the keyboard in my Paint() routine. I haven't found
how to do it with Qt. I thought of having a map which would
be updated in keyPressEvent and keyReleaseEvent and poll that map in
Paint().
Your second method is what I would have done, except that I would use a continuous, periodic QTimer event to poll the keyboard-pressed map and call QWidget::Update() function when necessary to invalidate the display widget instead. Performing non-painting operations inside Paint() is strongly discouraged for many reasons but I do not know how to explain that well.
There is no Qt API for checking whether a key is pressed or not.
You may have to write separate code for different platforms and add a bit of #ifdef logic.
On Windows you can use GetKeyState() and GetKeyboardState(), both declared in windows.h.
This is not straight forward when using Qt, but the Gluon team has been working on exactly that problem (along with a bunch of others). GluonInput solves the issue, and is available as part of Gluon: http://gluon.gamingfreedom.org/ It is also a nice, Qt-like API, so while it's an extra dependency, it should be possible for you to use it.
This is caused by auto repeation of keys:
When I press and hold, for example, the forward key, the camera moves
forward "step" units, then halts for a while and then continues
moving.
In QT5 you can detect key held down by function isAutoRepeat() of QKeyEvent object. If the key is held down then isAutoRepeat() will return true.
for example:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->isAutoRepeat())
{
return;
}
if (!event->isAutoRepeat())
{
qDebug() << "[MainWindow::keyPressEvent()] " << event->key() << "; " << event->isAutoRepeat();
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if (event->isAutoRepeat())
{
return;
}
qDebug() << "[MainWindow::keyReleaseEvent()] " << event->key() << "; " << event->isAutoRepeat();
}
Use QGuiApplication::keyboardModifiers() and QGuiApplication::queryKeyboardModifiers() for keyboard modifiers in Qt5