Sorting elements of a tree control

The basic mechanism for sorting elements of a tree control is the method Sort-Children(item). The item parameter is, as you should expect by now, an instance of wx.TreeItemId. The method sorts the children of that item from the top of the list downward in alphabetical order of their display strings.

There's one quirk to sorting in a tree control. In order for a tree to sort, each tree item needs to have data attached, which is true even if you are going to use the default sort. In the default case, the attached data is merely None, but for sorting to work, you still need to explicitly set that in the tree control.

In section 15.1, we mentioned that the methods that allow you to create a tree item also allow you to associate the item with an arbitrary data object. We also told you not to use that mechanism. The data item is of the type wx.TreeItemData. If you were programming in C + +, you'd create a subclass of wx.TreeItemData that wrapped your actual data item. Since you are not programming in C + +, there's a predefined set of shortcuts in wxPython that you can use to associate a Python object with a tree item.

The shortcut setter method is SetItemPyData(item, obj). You pass this method a wx.TreeItemId and an arbitrary Python object, and wxPython manages the association behind the scenes. When you want the data item back, you call GetItem-PyData(item), which returns the Python object.

ADVANCED There is a special wxPython constructor for wx.TreeItemData that takes NOTE a Python object: wx.TreeItemData(obj). You can then use the Get-ItemData(item) and SetItemData(item, obj) methods to manage the Python data. This is the mechanism that the SetItemPyData() method uses behind the scenes. This information may be useful to you at some point, but for the most part you can get by with the py data methods.

To use the associated data for sorting your tree, your tree must be a custom subclass of wx.TreeCtrl, and you must override the method OnCompareItems(item1, item2). The two parameters are wx.TreeItemId instances of the two items being compared. The return value is -1 if item1 should sort before item2, 1 if item1 should sort after item2 and 0 if the two items are equal. This method is automatically called by the tree control when it sorts to calculate each comparison. You can do whatever you want within the OnCompareItems() method. Specifically, you can call GetItemPyData() to get the associated data methods for each item, as in the following:

def OnCompareItems(self, item1, item2); data1 = self.GetItemPyData(item1) data2 = self.GetItemPyData(item2) return cmp(data1, data2)

This snippet sorts the tree based on whatever the Python comparison function returns for data1 and data2.

Was this article helpful?

+1 0


  • sara
    How to sort treectrl wxpython?
    8 years ago
  • yvonne
    How do you sort wxpython tree control?
    6 months ago

Post a comment