From 7c4446ae0ddb2b4f03ce818bff88e4ef2a914f01 Mon Sep 17 00:00:00 2001 From: beyondcompute Date: Mon, 22 Dec 2025 06:23:39 +0200 Subject: [PATCH] Add global Ctrl/Cmd+W handler to close active window/dialog Before this change, developer needed to add such a handler to each window/dialog separately --- qt/aqt/__init__.py | 16 ++++++++++++++++ qt/aqt/main.py | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/qt/aqt/__init__.py b/qt/aqt/__init__.py index 53bdc3c92..11193cb00 100644 --- a/qt/aqt/__init__.py +++ b/qt/aqt/__init__.py @@ -407,6 +407,22 @@ class AnkiApp(QApplication): def eventFilter(self, src: Any, evt: QEvent | None) -> bool: assert evt is not None + # Handle Close shortcut here because modal dialogs disable main-window shortcuts + if (is_mac or is_lin) and evt.type() == QEvent.Type.KeyPress: + key_event = cast(QKeyEvent, evt) + if not key_event.isAutoRepeat(): + mods = cast(int, key_event.modifiers().value) + seq = QKeySequence(mods | key_event.key()) + if any( + seq == binding + for binding in QKeySequence.keyBindings( + QKeySequence.StandardKey.Close + ) + ): + if mw is not None: + mw._close_active_window() + return True + pointer_classes = ( QPushButton, QCheckBox, diff --git a/qt/aqt/main.py b/qt/aqt/main.py index c707d1b2a..df55b68f6 100644 --- a/qt/aqt/main.py +++ b/qt/aqt/main.py @@ -1184,6 +1184,22 @@ title="{}" {}>{}""".format( self.applyShortcuts(globalShortcuts) self.stateShortcuts: list[QShortcut] = [] + def _close_active_window(self) -> None: + window = ( + QApplication.activeModalWidget() + or current_window() + or self.app.activeWindow() + ) + if not window or window is self: + return + if window is getattr(self, "profileDiag", None): + # Do not allow closing of ProfileManager + return + if isinstance(window, QDialog): + window.reject() + else: + window.close() + def _normalize_shortcuts( self, shortcuts: Sequence[tuple[str, Callable]] ) -> Sequence[tuple[QKeySequence, Callable]]: