[wxPython-users] Re: Sorted List Control - how?

Peter Hansen peter at engcorp.com
Sun Dec 10 10:19:42 PST 2006


Donn Ingle wrote:
>> The docs show a SortItems() call that does this.  (Note it doesn't
>> "maintain" it for you... you just call that method to ensure it is
>> sorted whenever you want it to be.)
> Thanks, I dunno how I missed that one. I'll go have another look.

The interface for wxPython might be non-obvious, especially to a 
beginner (not sure if you are one or not).  Here's a trivialized example 
you can probably build on, which should explain what the note about "a 
callable object" means in the C++ docs:

Define a sorter class, something like this.  It exists basically so 
__call__() can be defined for it:

class _StepSorter(object):
     '''used in call to ListCtrl.SortItems()'''
     def __call__(self, a, b):
         # a and b were set by ListCtrl.SetItemData()
         return cmp(a, b)

# when you insert/add items into the list, call SetItemData for them
# since that's what SortItems() passes to the sorter object:

     index = self.listCtrl.InsertStringItem(0, 'some string')
     self.listCtrl.SetItemData(index, someValue)

     # elsewhere in your code...
     stepSorter = _StepSorter()	# could create this once and save

     # now do the sort itself
     self.listCtrl.SortItems(stepSorter)

At this point the list items are sorted according to how your __call__() 
comparator method in the sorter compares the values passed in, which are 
the values you passed to SetItemData().  I don't know whether you can 
pass in values that are not integers, not having tried it, but the docs 
suggest you won't be able to, so if you wanted to compare the strings 
themselves (e.g. for alphabetical order) you'd probably need to make 
someValue the same as index, and index into an array of strings that 
you'd store elsewhere, or look them up directly with GetItemText() or 
something.  I haven't worked with this feature a lot... just hoping this 
helps a little.  (My list items were basically images with numbers as 
labels, and I just wanted them sorted numerically so it was simple.)

-Peter




More information about the wxpython-users mailing list