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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With