sunyata
sunyata

Reputation: 2251

Detecting the right shift key in Qt

Is it possible to capture the right shift key only in Qt?

In the list of values for the Qt::Key enum there's Key_Shift (also Key_Kana_Shift and Key_Eisu_Shift but they seem to be for Japanese keyboards) but I don't know how to distinguish between the right and the left shift key, is this even possible?

I would like to find a solution which works for the major platforms (GNU/Linux, Windows, MacOS)

Grateful for help and with kind regards, Tord

Upvotes: 3

Views: 2834

Answers (2)

Nikos C.
Nikos C.

Reputation: 51850

Qt does not provide a portable name for these keys. However, it does give you access to the platform-specific scancodes for the keys. This is done through QKeyEvent::nativeScanCode(). In your QWidget::keyPressEvent() function, add some temporary code to print the scan code of the keys you press:

#include <QDebug>
#include <QKeyEvent>
void YourWidgetClass::keyPressEvent(QKeyEvent *event)
{
    qDebug() << event->nativeScanCode();
    event->accept();
}

Now run your program and press the shift keys. Here on my system (Linux/X11), left shift has the code 50, right shift has the code 62. So that means you can check for those:

void YourWidgetClass::keyPressEvent(QKeyEvent *event)
{
    switch (event.nativeScanCode()) {
    case 50: // left shift
    case 62: // right shift
    }
}

These codes will be the same on all Linux systems running in X11 using XCB. They might be different on other Linux systems (like those running Wayland instead of X11.) And they are different on Windows too, though all Windows versions use (AFAIK) the same codes. You can Google for what the scan codes are on Windows. Note that scan codes are usually documented in hex, so when you see "30", you should use "0x30" in your code.

You can't do this on Mac OS though. On Mac OS, you would need to use a non-Qt API to get the code.

Upvotes: 1

Karpo22
Karpo22

Reputation: 11

If you are coding on a Windows OS, then you can use the the nativeVirtualKey() const type. Windows provides identifiers for the individual keys that are pressed, including the left and right shift key (VK_LSHIFT and VK_RSHIFT respectively) https://msdn.microsoft.com/en-us/library/ms927178.aspx. By accessing the virtual keys of your key press event similarly to this:

if (event->nativeVirtualKey() == VK_LSHIFT) {
// left shift specific code
} else if (event->nativeVirtualKey() == VK_RSHIFT) {
// right shift specific code
}

Upvotes: 1

Related Questions