wxPython List Control, Data Items, and Sorting

After adding the LC_SORT_ASCENDING style to a list control I started to see some odd behavior. Some items would not drag-n-drop while other drag-n-drops dropped the wrong item! This is what happend:

Originally the list was unsorted. Since the data portion of items in a list control must be an integer (due to the underlying C++ wXWindows implementation), I had simply set the data portion to the index returned by InsertStringItem:


index = self.InsertStringItem( sys.maxint,  anObject.name )
self.SetItemData(index, index) 
self.dataMap[index] = anObject

Now this works fine as long as the ordering of the list control does not change. Naturally it does when you later go back and set the style to sorted! Once this style is set, you may receive the same index back multiple times from InsertStringItem. This sometimes overwrote entries in self.dataMap, causing the problems with drag-n-drop.

The solution was simple – when loading the list, keep your own index, incrementing it as items are added. Set the data for a given entry to this index and use this same index, not the one returned from InsertStringItem, to index the dataMap:


        self.dataMap = {}
        dataMapIndex=0
        for object in listOfObjectsToAdd:
              index = self.InsertStringItem( sys.maxint, object.name )
              self.SetItemData(index, itemDataMapIndex)
              self.dataMap[dataMapIndex]=( clip )
              dataMapIndex += 1

So now no matter how the list is reordered, the data associated with an entry will be the correct key into the dataMap.

I hope this tip may save others some time debugging, even though it is probably obvious to someone with wxPython/wxWindows experience.

This entry was posted in Python, wxPython. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *