0

I'm trying to implement a settings menu which should open on pressing keys of ctrl+, of the standard US layout on any layout. But on non-US layout it opens on different keys. Is there a way to achieve this?

from PySide6.QtGui import QAction, QKeySequence
from PySide6.QtWidgets import QApplication, QMainWindow


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        menubar = self.menuBar()
        file_menu = menubar.addMenu("File")

        settings_action = QAction("Preferences", self)
        settings_action.setMenuRole(QAction.MenuRole.PreferencesRole)

        settings_key = QKeySequence(QKeySequence.StandardKey.Preferences)

        if not settings_key.toString():
            settings_key = QKeySequence("Ctrl+,")

        settings_action.setShortcut(settings_key)
        settings_action.triggered.connect(lambda: print("Opened"))

        file_menu.addAction(settings_action)


if __name__ == "__main__":
    app = QApplication()

    window = MainWindow()
    window.show()

    app.exec()
4
  • What exactly do you expect to happen if the keyboard layout does not have the comma as a top-level character key? See: Keyboard Layout Issues. Commented Aug 16 at 21:39
  • I don't need comma in a specific layout. On a specific layout, it should be a character that is comma on US. Commented Aug 17 at 7:54
  • 1
    So, you want a shortcut that is triggered using the key that is on the right of "M" in the QWERTY layout, no matter the actual layout in use? That's technically doable, but presents some important issues: 1. in order to rely on a key position (instead of the actual character for the current layout) you need to use scancodes, and while most keyboard share the same structure, there's no guarantee that it will be reliable everywhere (also, some drivers/OS remap scancodes); 2. QKeySequence cannot be constructed using scancodes, so you cannot use QShortcut to begin with, unless you're prepared to » Commented Aug 17 at 16:10
  • 1
    » create your own mapping for that specific key on all known layouts, and hope that detecting the input locale may be a valid guess; 3. on some layouts, that key combination may have a different meaning or usage, or you may be even already using that combination: for instance, on DVORAK that key combination would become <ctrl+w>. Frankly, I would highly discourage to do that: making it work on any keyboard would be quite a difficult task (there's no 100% guarantee that it will always work on any keyboard), and has less benefits than drawbacks (starting from the difficulty of doing it). Commented Aug 17 at 16:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.