Get original key as though without shift modifier
Asked Answered
A

1

7

I want to create keyboard bindings, which work at least similarly on different keyboard layouts. My problem is that the shift modifier converts keys into different keys, as detailed in the documentation: http://doc.qt.io/qt-5/qkeysequence.html#keyboard-layout-issues

Is there any way to find out the original key irrespective of the keyboard layout? E.g. find out that . is pressed when shift+. is pressed.

See also this (currently unanswered) quesion: get shift+numerical keys in qt using qkeyevent

Aedes answered 6/3, 2017 at 17:53 Comment(0)
D
3

In Windows you can use MapVirtualKeyA and MAPVK_VK_TO_CHAR to get the unshifted key. MapVirtualKeyA needs the virtual key, which can be get using QKeyEvent::nativeVirtualKey.

Note: When pressing modifiers only QKeyEvent::key() may report a false character, the virtual key helps to distinguish these cases.

Example

void MainWindow::keyPressEvent(QKeyEvent* ke)
{
  const auto vk = ke->nativeVirtualKey();
  const auto unshifted_key = MapVirtualKeyA(vk, MAPVK_VK_TO_CHAR);

  qDebug() << "Original key:" << (char)ke->key();
  qDebug() << "Unshifted key:" << (char)unshifted_key;

  if (unshifted_key > 0) { 
    // Printing the full key sequence just for comparison purposes
    QString modifier;
    if (ke->modifiers() & Qt::ShiftModifier) modifier += "Shift+";
    if (ke->modifiers() & Qt::ControlModifier) modifier += "Ctrl+";
    if (ke->modifiers() & Qt::AltModifier) modifier += "Alt+";
    if (ke->modifiers() & Qt::MetaModifier) modifier += "Meta+";
    const QKeySequence ks(modifier + QChar(ke->key()));
    qDebug() << "Full key sequence:" << ks.toString();
  }
}

The full source code for the example can be found in here.

Derosa answered 26/3, 2019 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.