Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get original key as though without shift modifier

Tags:

c++

qt

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

like image 390
GPMueller Avatar asked Nov 09 '22 01:11

GPMueller


1 Answers

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.

like image 116
cbuchart Avatar answered Nov 15 '22 07:11

cbuchart