diff --git a/src/app_model/backends/qt/_qaction.py b/src/app_model/backends/qt/_qaction.py index 6e96c07..d83f6ce 100644 --- a/src/app_model/backends/qt/_qaction.py +++ b/src/app_model/backends/qt/_qaction.py @@ -188,6 +188,17 @@ def __init__( with contextlib.suppress(NameError): self.update_from_context(self._app.context) + self._app.destroyed.connect(self._on_app_destroyed) + + def _on_app_destroyed(self) -> None: + # To not keep object alive after the app is destroyed, + # we remove the parent, which will + # trigger the deletion of this object. + # We ignore RuntimeError, which is raised if + # the Qt object has already been deleted. + with contextlib.suppress(RuntimeError): # Qt object already deleted + self.setParent(None) + @staticmethod def _cache_key(app: Application, menu_item: MenuItem) -> tuple[int, int]: return (id(app), hash(menu_item)) diff --git a/tests/test_qt/test_qactions.py b/tests/test_qt/test_qactions.py index 6d3cb2e..e1b19e3 100644 --- a/tests/test_qt/test_qactions.py +++ b/tests/test_qt/test_qactions.py @@ -4,6 +4,7 @@ import pytest from qtpy.QtGui import QColor +from app_model import Application from app_model.backends.qt import QCommandRuleAction, QMenuItemAction from app_model.types import ( Action, @@ -16,7 +17,6 @@ ) if TYPE_CHECKING: - from app_model import Application from conftest import FullApp @@ -202,3 +202,19 @@ def test_update_keybinding_in_tooltip( dispose1() q_action._update_keybinding() assert q_action.toolTip() == "Initial tooltip" + + +def test_clean_parent_on_app_destroyed(qapp) -> None: + app = Application("test_clean_parent") + action = Action( + id="test.clean.parent", + title="Test clean parent", + callback=lambda: None, + ) + app.register_action(action) + + q_action = QMenuItemAction.create(MenuItem(command=action), app, parent=qapp) + assert q_action.parent() is qapp + + Application.destroy(app.name) + assert q_action.parent() is None