Tuesday 15 August 2023

How to get the key without modifiers on keyPressEvent in qt?

Consider this pyside6 example:

from PySide6.QtCore import *  # noqa
from PySide6.QtGui import *  # noqa
from PySide6.QtWidgets import *  # noqa


class TableWidget(QTableWidget):
    def __init__(self):
        super().__init__()
        self.setColumnCount(2)
        self.setHorizontalHeaderLabels(["Key", "Value"])
        self.setColumnWidth(1, 800)
        self._sequence_format = QKeySequence.PortableText
        self._modifier_order = [
            self.modifier_to_string(modifier)
            for modifier in (Qt.ControlModifier, Qt.AltModifier, Qt.ShiftModifier)
        ]

    def modifier_to_string(self, modifier):
        return QKeySequence(modifier.value).toString(self._sequence_format).lower()

    def key_to_string(self, key):
        if key in (
            Qt.Key_Shift,
            Qt.Key_Control,
            Qt.Key_Alt,
            Qt.Key_Meta,
            Qt.Key_AltGr,
        ):
            return None
        else:
            return QKeySequence(key).toString(self._sequence_format).lower()

    def shortcut_from_event(self, event):
        key = event.key()
        modifiers = event.modifiers()
        vk = event.nativeVirtualKey()
        key_string = self.key_to_string(key)
        vk_string = self.key_to_string(vk)
        modifier_strings = tuple(
            self.modifier_to_string(modifier) for modifier in modifiers
        )
        shortcut_tpl = (key_string, modifier_strings)

        shortcut_lst = []
        for modifier_string in self._modifier_order:
            if modifier_string in shortcut_tpl[1]:
                shortcut_lst.append(modifier_string)
        shortcut_lst.append(shortcut_tpl[0])
        if None in shortcut_lst:
            shortcut = None  # noqa
        else:
            shortcut = "".join(shortcut_lst)  # noqa

        return {
            "shortcut": shortcut,
            "key": key,
            "modifiers": modifiers,
            "vk": vk,
            "key_string": key_string,
            "vk_string": vk_string,
            "modifier_strings": modifier_strings,
        }

    def keyPressEvent(self, event):
        table = self
        item = self.shortcut_from_event(event)

        if item:
            table.clearContents()
            table.setRowCount(0)

            row_position = 0
            for k, v in sorted(item.items(), reverse=True):
                table.insertRow(row_position)
                table.setItem(row_position, 0, QTableWidgetItem(k))
                table.setItem(row_position, 1, QTableWidgetItem(str(v)))
            # table.resizeColumnsToContents()

        # return super().keyPressEvent(event)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    w = TableWidget()
    w.resize(800, 600)
    w.show()
    sys.exit(app.exec())

I'd like to know how i can create a shortcut string using the modifiers that follows the modifier_order and the unaffected key string, for instance, right now:

  • If I press key '+'

enter image description here

  • If I press shift + '+'

enter image description here

  • If I press altgr + '+'

enter image description here

But I'd like to modify the code so the shortcut created will be '+', 'shift+plus' and 'ctrl+alt+plus' respectively

How can I achieve this behaviour? Similar to all keys, i'd like to get the string of the unaffected key without any modifiers on top



from How to get the key without modifiers on keyPressEvent in qt?

No comments:

Post a Comment