From 27a7cfc489b1f2fc874e2ca0559b088f700180ae Mon Sep 17 00:00:00 2001 From: Dave Pearson Date: Thu, 5 Jan 2023 10:35:25 +0000 Subject: [PATCH] Add a public read-only parent property to TreeNode See #1397. --- CHANGELOG.md | 10 ++++++++-- src/textual/widgets/_tree.py | 5 +++++ tests/tree/test_tree_node_parent.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 tests/tree/test_tree_node_parent.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ee7b9a673..6252355427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [0.10.0] - Unreleased + +### Added + +- Added `TreeNode.parent` -- a read-only property for accessing a node's parent https://github.com/Textualize/textual/issues/1397 + ## [0.9.1] - 2022-12-30 ### Added @@ -23,8 +29,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Widget.render_line now returns a Strip - Fix for slow updates on Windows -- Bumped Rich dependency - +- Bumped Rich dependency + ## [0.8.2] - 2022-12-28 ### Fixed diff --git a/src/textual/widgets/_tree.py b/src/textual/widgets/_tree.py index e23385502c..f6638ca9ca 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