[wxPython-users] Re: Re: Sorted List Control - how?
Robin Dunn
robin at alldunn.com
Tue Dec 12 12:52:18 PST 2006
Donn Ingle wrote:
>> A "callable object" doesn't have to be a class with a __call__ method.
>> It is anything that can be called, IOW, any foo for which foo(a,b) is
>> possible.
> Robin,
> If all that ca get passed to foo is a and b - which are numbers assigned
> during a SetItemData call, how can one achieve an alphabetical sort?
Because of the unfortunate decision made years ago to model the
wxListCtrl API on the Win32 ListView API we are stuck with some a bad
design issues until we have something that can replace the wxListCtrl.
One of those is that each items' data value is what is passed to the
sort function rather than something like the item indexes or whatever.
So the way to work with this wart, instead of against it, is to maintain
something that will allow you to map from the item data value to the
item or the item's textual values. The Python dictionary is perfect for
this, and is how it is done in the ListCtrl.py sample in the demo. Then
you simply have to assign each item a unique numerical value as a data
value, and make that value a key in a dictionary that maps to the values
or objects you want to use for sorting. Then your sort function simply
looks something like this:
def SortCompare(self, key1, key2):
value1 = self.valueMap[key1]
value2 = self.valueMap[key2]
return cmp(value1, value2)
Of course you can use something besides a dictionary to get from the key
to the value, if that makes more sense for your app. Also if needed the
comparison can be much more complex as well, for secondary sorts using
values in other columns, etc.
> I mean - let's assume everything I put into the listctrl up-front gets the
> numbers 1 to 10 as the items go into it; later-on I want to add a new item.
> How do I know what number to give the new item such that it will sort into
> the listctrl?
> Let's say the new item should fit between 3 and 4 in the list. How do I know
> this?
You don't need to know. Just give it a new key value of 11 (or
whatever) that maps to the sortable values, and then call SortItems
again. The key will get mapped to the text to sort by and the item will
get shuffled into place.
--
Robin Dunn
Software Craftsman
http://wxPython.org Java give you jitters? Relax with wxPython!
More information about the wxpython-users
mailing list