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
This commit is contained in:
beyondcompute 2025-12-22 06:23:39 +02:00
parent 8f2144534b
commit 7c4446ae0d
2 changed files with 32 additions and 0 deletions

View file

@ -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,

View file

@ -1184,6 +1184,22 @@ title="{}" {}>{}</button>""".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]]: