diff --git a/CHANGELOG.md b/CHANGELOG.md index fa82c5ab1a..f852ea6d5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added +- Added `TreeNode.parent` -- a read-only property for accessing a node's parent https://github.com/Textualize/textual/issues/1397 - Added public `TreeNode` label access via `TreeNode.label` https://github.com/Textualize/textual/issues/1396 ### Changed diff --git a/src/textual/widgets/_tree.py b/src/textual/widgets/_tree.py index e7ac669dc9..39b63a0376 100644 --- a/src/textual/widgets/_tree.py +++ b/src/textual/widgets/_tree.py @@ -121,6 +121,11 @@ def id(self) -> NodeID: """NodeID: Get the node ID.""" return self._id + @property + def parent(self) -> TreeNode[TreeDataType] | None: + """TreeNode[TreeDataType] | None: The parent of the node.""" + return self._parent + @property def is_expanded(self) -> bool: """bool: Check if the node is expanded.""" diff --git a/tests/tree/test_tree_node_parent.py b/tests/tree/test_tree_node_parent.py new file mode 100644 index 0000000000..90353ea92a --- /dev/null +++ b/tests/tree/test_tree_node_parent.py @@ -0,0 +1,10 @@ +from textual.widgets import TreeNode, Tree + +def test_tree_node_parent() -> None: + """It should be possible to access a TreeNode's parent.""" + tree = Tree[None]("Anakin") + child = tree.root.add("Leia") + grandchild = child.add("Ben") + assert tree.root.parent is None + assert grandchild.parent == child + assert child.parent == tree.root