diff --git a/src/magicgui/backends/_ipynb/widgets.py b/src/magicgui/backends/_ipynb/widgets.py index 3a49de646..93af80acf 100644 --- a/src/magicgui/backends/_ipynb/widgets.py +++ b/src/magicgui/backends/_ipynb/widgets.py @@ -59,7 +59,10 @@ def _mgui_set_enabled(self, enabled: bool): def _mgui_get_parent(self): # TODO: how does ipywidgets handle this? - return getattr(self._ipywidget, "parent", None) + # return getattr(self._ipywidget, "parent", None) + raise NotImplementedError( + "parent not implemented for ipywidgets backend. Please open an issue" + ) def _mgui_set_parent(self, widget): # TODO: how does ipywidgets handle this? diff --git a/src/magicgui/backends/_qtpy/widgets.py b/src/magicgui/backends/_qtpy/widgets.py index da2ff2b1f..71ce796b6 100644 --- a/src/magicgui/backends/_qtpy/widgets.py +++ b/src/magicgui/backends/_qtpy/widgets.py @@ -26,6 +26,7 @@ from magicgui.types import FileDialogMode from magicgui.widgets import Widget, protocols +from magicgui.widgets._concrete import _LabeledWidget if TYPE_CHECKING: import numpy @@ -82,9 +83,18 @@ def _mgui_get_enabled(self) -> bool: def _mgui_set_enabled(self, enabled: bool) -> None: self._qwidget.setEnabled(enabled) - # TODO: this used to return _magic_widget ... figure out what we should be returning - def _mgui_get_parent(self) -> QObject | None: # type: ignore - return self._qwidget.parent() + def _mgui_get_parent(self) -> Widget | None: + par = self._qwidget.parent() + # FIXME: This whole thing is hacky. + while par is not None: + mgui_wdg = getattr(par, "_magic_widget", None) + # the labeled widget itself should be considered a "hidden" layer. + if isinstance(mgui_wdg, Widget) and not isinstance( + mgui_wdg, _LabeledWidget + ): + return mgui_wdg + par = par.parent() + return None def _mgui_set_parent(self, widget: Widget) -> None: self._qwidget.setParent(widget.native if widget else None) diff --git a/tests/test_container.py b/tests/test_container.py index c0ea4db1c..15a2b205f 100644 --- a/tests/test_container.py +++ b/tests/test_container.py @@ -203,3 +203,14 @@ def _on_clicked(self): ... assert isinstance(C(), widgets.Container) + + +def test_parent(): + lbl = widgets.Label() + inner = widgets.Container(widgets=[lbl]) + outer = widgets.Container() + outer.append(inner) + + assert lbl.parent is inner + assert inner.parent is outer + assert outer.parent is None diff --git a/tests/test_widgets.py b/tests/test_widgets.py index b41f8e4d2..60abd1fc2 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -198,7 +198,7 @@ def test_basic_widget_attributes(): assert widget.parent is None container.append(widget) - assert widget.parent is container.native + assert widget.parent is container widget.parent = None assert widget.parent is None assert widget.label == "my name"