Finding Certain Child In Wxtreectrl And Updating Treectrl In Wxpython
How can I check if a certain root in a wx.TreeCtrl object has a certain child or not? I am writing manual functions to update TreeCtrl every time a child is added by user.Is there
Solution 1:
You might want to consider storing the data in some other easily-searchable structure, and using the TreeCtrl
just to display it. Otherwise, you can iterate over the children of a TreeCtrl
root item like this:
defitem_exists(tree, match, root):
item, cookie = tree.GetFirstChild(root)
while item.IsOk():
if tree.GetItemText(item) == match:
returnTrue#if tree.ItemHasChildren(item):# if item_exists(tree, match, item):# return True
item, cookie = tree.GetNextChild(root, cookie)
returnFalse
result = item_exists(tree, 'some text', tree.GetRootItem())
Uncommenting the commented lines will make it a recursive search.
Solution 2:
A nicer way to handle recursive tree traversal is to wrap it in a generator object, which you can then re-use to perform any operation you like on your tree nodes:
defwalk_branches(tree,root):
""" a generator that recursively yields child nodes of a wx.TreeCtrl """
item, cookie = tree.GetFirstChild(root)
while item.IsOk():
yield item
if tree.ItemHasChildren(item):
walk_branches(tree,item)
item,cookie = tree.GetNextChild(root,cookie)
for node in walk_branches(my_tree,my_root):
# do stuff
Solution 3:
For searching by text without recursion :
def GetItemByText(self, search_text, tree_ctrl_instance):
retval = None
root_list = [tree_ctrl_instance.GetRootItem()]
for root_child in root_list:
item, cookie = tree_ctrl_instance.GetFirstChild(root_child)
while item.IsOk():
if tree_ctrl_instance.GetItemText(item) == search_text:
retval = item
break
if tree_ctrl_instance.ItemHasChildren(item):
root_list.append(item)
item, cookie = tree_ctrl_instance.GetNextChild(root_child, cookie)
return retval
Post a Comment for "Finding Certain Child In Wxtreectrl And Updating Treectrl In Wxpython"