简体   繁体   中英

Get Path to Item on a TreeCtrl

Lets say I have this treeCtrl:

Root

    Dogs
        Pug
        Lab

    Birds
        Parrot
        Eagle

How can I get a the path to the pug item?

EX: I should get something like,

["root","Dogs","Pug"]

(But using TreeCtrlIds)

Is there a function like,

getTreePath(Item) ?

You can iteratively call GetItemParent(item) to get from the item to the root node as follows (Source: TreeCtrl api ):

root = myTree.GetRootItem()
pathList = [item]
done = False
while not done:
    path = myTree.GetItemParent(item)
    pathList.append(path)
    if path==root:
        done=True

Note this will give you the items in the reverse of the order you require, use pathList.reverse() to correct for this.

Edit:

  1. As @gddc points out, instead of pathList.append(path) , you can use pathList.insert(0, path) to avoid reversing your list.
  2. If you're only interested in the path names, append only each item's text using GetItemText() instead of the entire object.

I use an iterative approach as well, but start with the currently selected item. It looks something like this:

pieces = []
item = self.tree.GetSelection()

while self.tree.GetItemParent(item):
  piece = self.tree.GetItemText(item)
  pieces.insert(0, piece)
  item = self.tree.GetItemParent(item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM