lördag 8 juli 2017

Using wxPython

I have been fiddling with wxPython which is a quite nice cross-platform GUI toolkit for Python. The main issue, however, is that it is fairly poorly documented with very few up-to-date examples and very minimal information in the class documentation. Thus, in this post I will discuss things as I go along which I have found out, but where I experienced the documentation lacking. Perhaps it will help someone some day.

Using ListCtrl

ListCtrl can be used to create complex list views as in other GUI tool kits. I wanted to make a list where multiple items can be selected. This can be done, and is actually in version 3/Phoenix which I am using the default mode. However, it was very hard for me to figure out how to read out which items were selected. GetIndex() in the emitted event only returns the index of the last selected item, and there is no GetIndices() or anything like that. The solution is to use the method GetNextSelected() which is in the ListCtrl class, not in the emitted event.
This method is kind of silly,  not very pythonic since one has to call it multiple times and increment an index every time to where the method should start looking. One can get out a list of all selected items with the code:
items = list()
i = my_listctrl.GetNextSelected(-1)
        while i != -1:
            items.append(i)
            i = my_listctrl.GetNextSelected(i)
I recommend wrapping this into a generator function like:
def GetIndices(listctrl):
    i = listctrl.GetNextSelected(-1)
    while i!= -1:
        yield i
        i = listctrl.GetNextSelected(i)
If you really need a list, make it one using:
list(GetIndices(my_listctrl))

Inga kommentarer: