Source code for radioviz.services.signal_blocker

#  Copyright 2025–2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2
"""
Signal blocking utility for Qt widgets.

This module provides a context manager to temporarily block signals
for Qt widgets during programmatic updates. This prevents unwanted
signal emissions that could trigger unwanted side effects during
bulk operations on UI elements.
"""

from __future__ import annotations

from types import TracebackType
from typing import Literal

from PySide6.QtCore import QObject


[docs] class SignalBlocked: """ A context manager to block signals for one or more QObject widgets while a block of code is executed. This context manager temporarily disables signal emission for the specified widgets, allowing safe programmatic updates without triggering connected slots. Usage:: with SignalBlocked(widget1, widget2, ...): # Code that changes widget values programmatically widget1.setCurrentText('New Value') widget2.setValue(100) """ def __init__(self, *widgets: QObject) -> None: """ Initializes the context manager with a list of QObject instances. :param widgets: Variable number of QObject instances to block signals for :type widgets: QObject """ # Store the list of widgets self.widgets: list[QObject] = [w for w in widgets if isinstance(w, QObject)] def __enter__(self) -> None: """ This method is executed when the 'with' block is entered. It blocks signals for all provided widgets. """ for widget in self.widgets: widget.blockSignals(True) # This method typically returns 'self' or a resource, but here we return nothing. def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> Literal[False]: """ This method is executed when the 'with' block is exited (normally or due to an exception). It unblocks signals for all provided widgets. :param exc_type: Exception type :type exc_type: type :param exc_val: Exception value :type exc_val: BaseException :param exc_tb: Exception traceback :type exc_tb: TracebackType :return: False to propagate any exceptions :rtype: bool """ for widget in self.widgets: # We must ensure the object is still a QObject before trying to unblock if isinstance(widget, QObject): widget.blockSignals(False) # Returning False (or None) means any exception is propagated. # Returning True means any exception is suppressed. We let it propagate. return False