In order to implement customisable hotkeys in an application I’m looking for a way to capture and display key presses with modifiers.
Wat I have now is this customised QLineEdit
:
from PyQt6.QtWidgets import QApplication, QLineEdit
from PyQt6.QtGui import QKeyEvent, QKeySequence
from PyQt6.QtCore import Qt, QKeyCombination
class HKLineEdit(QLineEdit):
modifiers = {16777248, 16777249, 16777250, 16777251}
def keyPressEvent(self, event: QKeyEvent):
if event.isAutoRepeat():
return
if event.key() in self.modifiers:
return
seq = QKeySequence(event.keyCombination())
self.setText(seq.toString())
# alternative with native virtual key:
mods = Qt.KeyboardModifier(event.modifiers())
nv_key = Qt.Key(event.nativeVirtualKey())
seq = QKeySequence(QKeyCombination(mods, nv_key))
self.setText(seq.toString())
app = QApplication([])
window = HKLineEdit()
window.show()
app.exec()
This works fine but it’s not completely perfect for Shift-combinations.
For example Shift+2
is displayed as Shift+@
Is there a (cross-platform, cross-locale) way to display Shift-combinations with the ‘base key’ instead of the actual key?
Because it sounded appropriate I’ve tried to use event.nativeVirtualKey()
and that gives the desired result for alphanumeric keys, but for other keys the results are very unexpected. For example ,
gives ¼
, and '
gives Þ
with my standard US keyboard on Win10.
Please note that beyond the descriptive name I have no idea what a ‘native virtual key’ actually is and I couldn’t find an explanation.