From b3b3615dcbe93b6a2044235ae3a38682d41add8a Mon Sep 17 00:00:00 2001 From: wyzula-jan Date: Tue, 24 Nov 2026 09:53:46 +0000 Subject: [PATCH] fix(button_focus): space and enter no longer press buttons --- bec_widgets/applications/companion_app.py | 2 + bec_widgets/applications/main_app.py | 2 + bec_widgets/utils/button_focus.py | 82 ++++++++ .../widgets/services/bec_queue/bec_queue.py | 1 - tests/unit_tests/test_button_focus.py | 197 ++++++++++++++++++ 5 files changed, 283 insertions(+), 1 deletion(-) create mode 100644 bec_widgets/utils/button_focus.py create mode 100644 tests/unit_tests/test_button_focus.py diff --git a/bec_widgets/applications/companion_app.py b/bec_widgets/applications/companion_app.py index 52a6bbb0..d8844728 100644 --- a/bec_widgets/applications/companion_app.py +++ b/bec_widgets/applications/companion_app.py @@ -27,6 +27,7 @@ from qtpy.QtWidgets import QApplication import bec_widgets from bec_widgets.applications.launch_window import LaunchWindow from bec_widgets.utils.bec_dispatcher import BECDispatcher +from bec_widgets.utils.button_focus import disable_button_keyboard_focus from bec_widgets.utils.rpc_register import RPCRegister # isort: on @@ -109,6 +110,7 @@ class GUIServer: """ logger.info("Starting GUIServer", repr(self)) self.app = QApplication(sys.argv) + disable_button_keyboard_focus(self.app) # Space or Enter must never press a button startup_profiler.mark("QApplication") if darkdetect.isDark(): apply_theme("dark") diff --git a/bec_widgets/applications/main_app.py b/bec_widgets/applications/main_app.py index 4cc25891..21526571 100644 --- a/bec_widgets/applications/main_app.py +++ b/bec_widgets/applications/main_app.py @@ -15,6 +15,7 @@ from bec_widgets.applications.views.developer_view.developer_view import Develop from bec_widgets.applications.views.device_manager_view.device_manager_view import DeviceManagerView from bec_widgets.applications.views.dock_area_view.dock_area_view import DockAreaView from bec_widgets.applications.views.view import ViewBase, WaveformViewInline, WaveformViewPopup +from bec_widgets.utils.button_focus import disable_button_keyboard_focus from bec_widgets.utils.colors import apply_theme from bec_widgets.utils.error_popups import SafeSlot from bec_widgets.utils.guided_tour import GuidedTour @@ -455,6 +456,7 @@ def main(): # pragma: no cover app = QApplication([sys.argv[0], *qt_args]) app.setApplicationName("BEC") + disable_button_keyboard_focus(app) # Space or Enter must never press a button by accident startup_profiler.mark("QApplication") apply_theme("dark") startup_profiler.mark("theme applied") diff --git a/bec_widgets/utils/button_focus.py b/bec_widgets/utils/button_focus.py new file mode 100644 index 00000000..dec06e7d --- /dev/null +++ b/bec_widgets/utils/button_focus.py @@ -0,0 +1,82 @@ +""" +Buttons that Space and Enter never press. + +Qt's Fusion style (the default on Linux) gives a clicked button the keyboard focus, so a later +Space or Enter presses it again, e.g. queues a scan again or stops one. ``ButtonFocusStyle`` +changes that for every button of the application: + +- a click still moves the focus to the button, so a field being edited loses it as before: it + emits ``editingFinished``, and a later Enter no longer reaches it (e.g. no motor move after + Stop); +- Space, Select, Return and Enter on a button do nothing, also when it got the focus + programmatically; +- Tab skips buttons, also a radio button after a click (Qt lets Tab enter a radio group at its + focused button). Buttons that take no focus at all (e.g. the clear button of a line edit or a + spin box's settings button) keep it that way. Fields, spin boxes and combo boxes keep their + focus and keys; arrow keys still move the check within a focused radio group. +""" + +from __future__ import annotations + +from qtpy.QtCore import QEvent, Qt +from qtpy.QtWidgets import QAbstractButton, QApplication, QProxyStyle, QStyle + +ACTIVATION_KEYS = frozenset( + (Qt.Key.Key_Space, Qt.Key.Key_Select, Qt.Key.Key_Return, Qt.Key.Key_Enter) +) +KEY_EVENTS = (QEvent.Type.KeyPress, QEvent.Type.KeyRelease) +NO_TAB_FOCUS = ~Qt.FocusPolicy.TabFocus.value + + +class ButtonFocusStyle(QProxyStyle): + """The platform style, but buttons take the focus on a click only and ignore Space/Enter.""" + + # pylint: disable=invalid-name + def styleHint(self, hint, option=None, widget=None, return_data=None): + """Click focus as the default policy of buttons; every other hint unchanged.""" + if hint == QStyle.StyleHint.SH_Button_FocusPolicy: + return Qt.FocusPolicy.ClickFocus.value + return super().styleHint(hint, option, widget, return_data) + + def polish(self, widget): # pylint: disable=arguments-renamed + """ + Give every button click focus (also those that set a policy themselves, e.g. QToolButton + sets TabFocus) and filter its activation keys. A button that takes no focus keeps that. + """ + if isinstance(widget, QAbstractButton): + if widget.focusPolicy() != Qt.FocusPolicy.NoFocus: + widget.setFocusPolicy(Qt.FocusPolicy.ClickFocus) + widget.installEventFilter(self) + return super().polish(widget) + + def unpolish(self, widget): # pylint: disable=arguments-renamed + """Stop filtering a button that leaves this style.""" + if isinstance(widget, QAbstractButton): + widget.removeEventFilter(self) + return super().unpolish(widget) + + def eventFilter(self, obj, event): + """Swallow Space, Select, Return and Enter on buttons; keep Tab off them.""" + if not isinstance(obj, QAbstractButton): + return False + if event.type() == QEvent.Type.FocusOut: + # a focused auto-exclusive button (radio) adds TabFocus to itself on focus in + obj.setFocusPolicy(Qt.FocusPolicy(obj.focusPolicy().value & NO_TAB_FOCUS)) + return False + return event.type() in KEY_EVENTS and event.key() in ACTIVATION_KEYS + + +def disable_button_keyboard_focus(app: QApplication) -> None: + """ + Wrap the application's style in ButtonFocusStyle. Call it right after creating the + QApplication: buttons read the focus hint when they are created. + + Args: + app(QApplication): the application whose buttons Space and Enter should not press. + """ + if isinstance(getattr(app, "button_focus_style", None), ButtonFocusStyle): + return + name = app.style().name() # e.g. "fusion" or "macos"; empty for an unnamed custom style + style = ButtonFocusStyle(name) if name else ButtonFocusStyle() + app.setStyle(style) + app.button_focus_style = style # type: ignore[attr-defined] diff --git a/bec_widgets/widgets/services/bec_queue/bec_queue.py b/bec_widgets/widgets/services/bec_queue/bec_queue.py index 8d961a11..9e6b8a4a 100644 --- a/bec_widgets/widgets/services/bec_queue/bec_queue.py +++ b/bec_widgets/widgets/services/bec_queue/bec_queue.py @@ -582,7 +582,6 @@ class BECQueue(BECWidget, QWidget): layout.addWidget(self.pause_button) # actions that are rarely needed and cannot be undone sit in a menu, out of the way self.more_button = MoreButton("More queue actions", parent=self.header) - self.more_button.setFocusPolicy(Qt.FocusPolicy.TabFocus) # keyboard: Tab, then Space more_menu = QMenu(self.more_button) self.reset_action = QAction("Reset queue…", more_menu) self.reset_action.setToolTip( diff --git a/tests/unit_tests/test_button_focus.py b/tests/unit_tests/test_button_focus.py new file mode 100644 index 00000000..a36bc091 --- /dev/null +++ b/tests/unit_tests/test_button_focus.py @@ -0,0 +1,197 @@ +import subprocess +import sys +import textwrap +from unittest import mock + +from qtpy.QtCore import QEvent, Qt +from qtpy.QtGui import QFocusEvent, QKeyEvent +from qtpy.QtWidgets import QLineEdit, QPushButton, QStyle, QStyleFactory, QToolButton + +from bec_widgets.utils.button_focus import ButtonFocusStyle, disable_button_keyboard_focus + +# the style is application-wide and only read when a button is created: check it in an app of +# its own, so the test application of the other tests keeps its style +APP_CHECK = textwrap.dedent(""" + from qtpy.QtCore import Qt + from qtpy.QtTest import QTest + from qtpy.QtWidgets import ( + QApplication, QCheckBox, QComboBox, QLineEdit, QPushButton, QRadioButton, QSpinBox, + QToolButton, QVBoxLayout, QWidget, + ) + + from bec_widgets.utils.button_focus import ButtonFocusStyle, disable_button_keyboard_focus + from bec_widgets.widgets.utility.spinbox import decimal_spinbox + + app = QApplication([]) + + + def wait_for(condition): + for _ in range(200): + if condition(): + return + QTest.qWait(10) + raise AssertionError(condition) + + + platform_style = app.style().name() + new_fields = lambda: (QLineEdit(), QSpinBox(), QComboBox()) + platform_fields = [f.focusPolicy() for f in new_fields()] # a macOS combo box is TabFocus + disable_button_keyboard_focus(app) + style = app.button_focus_style + disable_button_keyboard_focus(app) # a second call keeps the one wrapper + assert app.button_focus_style is style and isinstance(style, ButtonFocusStyle) + assert style.baseStyle().name() == platform_style + + explicit = QPushButton() + explicit.setFocusPolicy(Qt.FocusPolicy.TabFocus) + for button in (QPushButton(), QToolButton(), QCheckBox(), QRadioButton(), explicit): + button.ensurePolished() # QToolButton sets TabFocus itself; polishing replaces it + assert button.focusPolicy() == Qt.FocusPolicy.ClickFocus, button + unfocusable = QToolButton() + unfocusable.setFocusPolicy(Qt.FocusPolicy.NoFocus) + unfocusable.ensurePolished() + assert unfocusable.focusPolicy() == Qt.FocusPolicy.NoFocus # an opt-out stays + fields = new_fields() + for field in fields: + field.ensurePolished() + assert [f.focusPolicy() for f in fields] == platform_fields # fields keep their own focus + + # a setpoint field next to Stop, a scan field next to Restore + form = QWidget() + layout = QVBoxLayout(form) + setpoint, stop, other = QLineEdit(form), QPushButton("Stop", form), QLineEdit(form) + tool, radio = QToolButton(form), QRadioButton("Fast", form) + search, spin = QLineEdit(form), decimal_spinbox.BECSpinBox(form) + search.setClearButtonEnabled(True) + for widget in (setpoint, stop, tool, radio, other, search, spin): + layout.addWidget(widget) + events = [] + stop.clicked.connect(lambda: events.append("stop")) + tool.clicked.connect(lambda: events.append("tool")) + setpoint.returnPressed.connect(lambda: events.append("move")) + setpoint.editingFinished.connect(lambda: events.append("edited")) + form.show() + form.activateWindow() + wait_for(form.isActiveWindow) + window = form.windowHandle() + + setpoint.setFocus() + wait_for(setpoint.hasFocus) + QTest.keyClicks(setpoint, "5") + QTest.mouseClick(stop, Qt.MouseButton.LeftButton) + assert events == ["edited", "stop"] # the field is left (and confirmed) before the click + assert stop.hasFocus() + for key in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter): + QTest.keyClick(window, key) + assert events == ["edited", "stop"] # no second stop, and no move from the setpoint + + QTest.mouseClick(tool, Qt.MouseButton.LeftButton) + QTest.keyClick(window, Qt.Key.Key_Space) + assert events[-1] == "tool" and events.count("tool") == 1 + + stop.setFocus() # e.g. a dialog that focuses a button itself + QTest.keyClick(window, Qt.Key.Key_Space) + QTest.keyClick(window, Qt.Key.Key_Return) + assert events.count("stop") == 1 + + QTest.mouseClick(radio, Qt.MouseButton.LeftButton) # Qt gives a focused radio TabFocus + setpoint.setFocus() + QTest.keyClick(window, Qt.Key.Key_Tab) + assert other.hasFocus() # Tab goes from field to field and skips the buttons + QTest.keyClick(window, Qt.Key.Key_Tab) + assert search.hasFocus() # also the tool button and the clicked radio button + + # buttons inside an editor take no focus: the editor keeps it and its keys + search.setFocus() + QTest.keyClicks(search, "samx") + clear = next(b for b in search.findChildren(QToolButton) if b.isVisible()) + clear.setFocus() # focused by code once: it must still not take the focus on a click + search.setFocus() + QTest.mouseClick(clear, Qt.MouseButton.LeftButton) + assert search.text() == "" and search.hasFocus() + QTest.keyClick(window, Qt.Key.Key_Space) + assert search.text() == " " + decimal_spinbox.QInputDialog.getInt = lambda *args: (2, False) # cancel the decimals dialog + spin.setValue(20) + spin.setFocus() + QTest.mouseClick(spin.setting_button, Qt.MouseButton.LeftButton) + assert spin.hasFocus() + QTest.keyClick(window, Qt.Key.Key_Up) + assert spin.value() == 21 + print("ok") + """) + + +def test_buttons_ignore_space_and_enter_and_fields_keep_their_focus(): + result = subprocess.run( + [sys.executable, "-c", APP_CHECK], capture_output=True, text=True, timeout=120 + ) + assert result.returncode == 0, result.stderr[-3000:] + assert result.stdout.strip().endswith("ok") + + +def test_button_focus_style_answers_click_focus_for_buttons_only(): + style = ButtonFocusStyle("fusion") + hint = QStyle.StyleHint.SH_Button_FocusPolicy + assert style.styleHint(hint) == Qt.FocusPolicy.ClickFocus.value + other = QStyle.StyleHint.SH_ToolTip_WakeUpDelay + assert style.styleHint(other) == style.baseStyle().styleHint(other) # the platform's + + +def test_polish_filters_activation_keys_on_buttons_only(qtbot): + style = ButtonFocusStyle("fusion") + button, field = QToolButton(), QLineEdit() + qtbot.addWidget(button) + qtbot.addWidget(field) + for widget in (button, field): + style.polish(widget) + assert button.focusPolicy() == Qt.FocusPolicy.ClickFocus # QToolButton itself says TabFocus + assert field.focusPolicy() == Qt.FocusPolicy.StrongFocus + + def key(kind, code): + return QKeyEvent(kind, code, Qt.KeyboardModifier.NoModifier) + + for code in (Qt.Key.Key_Space, Qt.Key.Key_Select, Qt.Key.Key_Return, Qt.Key.Key_Enter): + for kind in (QEvent.Type.KeyPress, QEvent.Type.KeyRelease): + assert style.eventFilter(button, key(kind, code)) + assert not style.eventFilter(field, key(kind, code)) + assert not style.eventFilter(button, key(QEvent.Type.KeyPress, Qt.Key.Key_A)) + assert not style.eventFilter(button, QEvent(QEvent.Type.Enter)) + + # Qt adds Tab to a focused radio button; leaving it takes only that away again + button.setFocusPolicy( + Qt.FocusPolicy(Qt.FocusPolicy.ClickFocus.value | Qt.FocusPolicy.TabFocus.value) + ) + assert not style.eventFilter(button, QFocusEvent(QEvent.Type.FocusOut)) + assert button.focusPolicy() == Qt.FocusPolicy.ClickFocus + + unfocusable = QToolButton() + qtbot.addWidget(unfocusable) + unfocusable.setFocusPolicy(Qt.FocusPolicy.NoFocus) + style.polish(unfocusable) + assert unfocusable.focusPolicy() == Qt.FocusPolicy.NoFocus + style.eventFilter(unfocusable, QFocusEvent(QEvent.Type.FocusOut)) # e.g. after setFocus() + assert unfocusable.focusPolicy() == Qt.FocusPolicy.NoFocus + + clicks = [] + pushed = QPushButton() + qtbot.addWidget(pushed) + pushed.clicked.connect(lambda: clicks.append(True)) + style.polish(pushed) + qtbot.keyClick(pushed, Qt.Key.Key_Space) + assert not clicks # the filter is installed on the button + style.unpolish(pushed) + qtbot.keyClick(pushed, Qt.Key.Key_Space) + assert clicks == [True] # and removed again + + +def test_disable_wraps_the_platform_style_once(): + for name in ("fusion", ""): # an unnamed custom style falls back to the platform default + app = mock.MagicMock(spec=["style", "setStyle"]) + app.style.return_value = QStyleFactory.create("fusion") + app.style.return_value.name = lambda name=name: name + disable_button_keyboard_focus(app) + disable_button_keyboard_focus(app) + app.setStyle.assert_called_once() + assert app.button_focus_style is app.setStyle.call_args.args[0] + assert isinstance(app.button_focus_style, ButtonFocusStyle)