Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example: global key event handler #111

Open
jamesdbrock opened this issue Feb 9, 2024 · 0 comments
Open

Example: global key event handler #111

jamesdbrock opened this issue Feb 9, 2024 · 0 comments

Comments

@jamesdbrock
Copy link
Member

jamesdbrock commented Feb 9, 2024

Here is an example of how to handle global keyboard events in an Edifice app.

KeyHandler = Callable[[QKeyEvent], None]

_global_key_handlers: set[KeyHandler] = set()


def handle_key_up_global(event: QKeyEvent) -> None:
    """
    Use this as the on_key_up event handler for the root Window component.

    Then children can use the use_key_up_global Hook to register their own global key handlers.
    """
    for handler in _global_key_handlers:
        handler(event)


def use_key_up_global(key: Qt.Key, key_up_handler: KeyHandler) -> None:
    """
    Hook to register a global key handler for key up events.

    Example::

        use_key_up_global(Qt.Key.Key_Escape, lambda _: go_back())

    """

    def handler(event: QKeyEvent) -> None:
        # https://doc.qt.io/qtforpython-6/PySide6/QtCore/Qt.html#PySide6.QtCore.PySide6.QtCore.Qt.Key
        if event.key() == key:
            event.accept()
            key_up_handler(event)

    def setup():
        _global_key_handlers.add(handler)

        def cleanup():
            _global_key_handlers.remove(handler)

        return cleanup

    use_effect(setup, (key, key_up_handler))
@component
def EscKey(self, on_escape: Callable[[], None]):
    """This component, when rendered, will globally handle Esc key events."""
    use_key_up_global(Qt.Key.Key_Escape, lambda _: on_escape())
    Label(text="Esc")

@component
def Main(self):
    with Window(
        title="My Application",
        on_key_up=handle_key_up_global,
    ):
        ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant