From 1d985abf26851c5d6321ffc572426844a73a321b Mon Sep 17 00:00:00 2001 From: Dave Pearson Date: Mon, 8 May 2023 08:44:29 +0100 Subject: [PATCH] Add TreeNode.remove This is for removing an individual node, via the node. Note that attempting to remove the root node of a Tree is an error and will case TreeNode.RemoveRootError to be raised. See #2462. --- src/textual/widgets/_tree.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/textual/widgets/_tree.py b/src/textual/widgets/_tree.py index 275fd15e5..df355ccdf 100644 --- a/src/textual/widgets/_tree.py +++ b/src/textual/widgets/_tree.py @@ -349,6 +349,21 @@ class TreeNode(Generic[TreeDataType]): node = self.add(label, data, expand=False, allow_expand=False) return node + class RemoveRootError(Exception): + """Exception raised when trying to remove a tree's root node.""" + + def remove(self) -> None: + """Remove this node from the tree. + + Raises: + TreeNode.RemoveRootError: If there is an attempt to remove the root. + """ + if self.is_root: + raise self.RemoveRootError("Attempt to remove the root node of a Tree.") + assert self._parent is not None + del self._parent._children[self._parent._children.index(self)] + self._tree._invalidate() + class Tree(Generic[TreeDataType], ScrollView, can_focus=True): """A widget for displaying and navigating data in a tree."""