mirror of
https://github.com/bec-project/bec_widgets.git
synced 2025-07-12 18:51:50 +02:00
feat(widget_io): utility function to find widget in the app by class
This commit is contained in:
@ -264,6 +264,48 @@ class WidgetIO:
|
||||
return WidgetIO._handlers[base]
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def find_widgets(widget_class: QWidget | str, recursive: bool = True) -> list[QWidget]:
|
||||
"""
|
||||
Return widgets matching the given class (or class-name string).
|
||||
|
||||
Args:
|
||||
widget_class: Either a QWidget subclass or its class-name as a string.
|
||||
recursive: If True (default), traverse all top-level widgets and their children;
|
||||
if False, scan app.allWidgets() for a flat list.
|
||||
|
||||
Returns:
|
||||
List of QWidget instances matching the class or class-name.
|
||||
"""
|
||||
app = QApplication.instance()
|
||||
if app is None:
|
||||
raise RuntimeError("No QApplication instance found.")
|
||||
|
||||
# Match by class-name string
|
||||
if isinstance(widget_class, str):
|
||||
name = widget_class
|
||||
if recursive:
|
||||
result: list[QWidget] = []
|
||||
for top in app.topLevelWidgets():
|
||||
if top.__class__.__name__ == name:
|
||||
result.append(top)
|
||||
result.extend(
|
||||
w for w in top.findChildren(QWidget) if w.__class__.__name__ == name
|
||||
)
|
||||
return result
|
||||
return [w for w in app.allWidgets() if w.__class__.__name__ == name]
|
||||
|
||||
# Match by actual class
|
||||
if recursive:
|
||||
result: list[QWidget] = []
|
||||
for top in app.topLevelWidgets():
|
||||
if isinstance(top, widget_class):
|
||||
result.append(top)
|
||||
result.extend(top.findChildren(widget_class))
|
||||
return result
|
||||
|
||||
return [w for w in app.allWidgets() if isinstance(w, widget_class)]
|
||||
|
||||
|
||||
################## for exporting and importing widget hierarchies ##################
|
||||
|
||||
|
@ -190,3 +190,23 @@ def test_widget_io_signal(qtbot, example_widget):
|
||||
toggle.checked = False
|
||||
qtbot.waitUntil(lambda: len(changes) > 4)
|
||||
assert changes[-1][1] == False
|
||||
|
||||
|
||||
def test_find_widgets(example_widget):
|
||||
# Test find_widgets by class type
|
||||
line_edits = WidgetIO.find_widgets(QLineEdit)
|
||||
assert len(line_edits) == 2 # one LineEdit and one in the SpinBox
|
||||
assert isinstance(line_edits[0], QLineEdit)
|
||||
|
||||
# Test find_widgets by class-name string
|
||||
combo_boxes = WidgetIO.find_widgets("QComboBox")
|
||||
assert len(combo_boxes) == 1
|
||||
assert isinstance(combo_boxes[0], QComboBox)
|
||||
|
||||
# Test non-recursive search returns the same widgets
|
||||
combo_boxes_flat = WidgetIO.find_widgets(QComboBox, recursive=False)
|
||||
assert combo_boxes_flat == combo_boxes
|
||||
|
||||
# Test search for non-existent widget returns empty list
|
||||
non_exist = WidgetIO.find_widgets("NonExistentWidget")
|
||||
assert non_exist == []
|
||||
|
Reference in New Issue
Block a user