How to create a list control (info)

Basic operation:

See Also:

Associating Python Data with Items (Phoenix)

When you need to associate data with an item:

   1 listctrl.SetItemData(item_by_index, integer_for_item)

Yep! You get to associate a WHOLE integer with the item!

To associate more, make a num generator (or use wx.NewIdRef) and keep a dict binding id to whatever data you want to associate.

So, for example:

   1 id = wx.NewIdRef()
   2 data_dict[id] = some_data_to_associate
   3 listctrl.InsertItem(index_to_place_at, string_name_of_item)
   4 listctrl.SetItemData(index_to_place_at, id)

So, now you can traverse:

index --> associated data (id) --> some_data_to_associate

Python Data Mixin

I'm surprised I haven't seen one of these yet.

   1 class ListCtrlPyDataMixin(object):
   2     def __init__(self):
   3         import sys
   4 
   5         self.id = -sys.maxint
   6         self.map = {}
   7 
   8         self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnDeleteItem)
   9         self.Bind(wx.EVT_LIST_DELETE_ALL_ITEMS, self.OnDeleteAllItems)
  10 
  11     def SetPyData(self, item, data):
  12         self.map[self.id] = data
  13         self.SetItemData(item, self.id)
  14         self.id += 1
  15 
  16     def SortPyItems(self, fn):
  17         from functools import wraps
  18 
  19         @wraps(fn)
  20         def wrapper(a, b):
  21             return fn(self.map[a], self.map[b])
  22 
  23         self.SortItems(wrapper)
  24 
  25     def OnDeleteItem(self, event):
  26         try:
  27             del self.map[event.Data]
  28         except KeyError:
  29             pass
  30         event.Skip()
  31 
  32     def OnDeleteAllItems(self, event):
  33         self.map.clear()
  34         event.Skip()

Have fun. -- ChristopherMonsanto

Selecting Items Programmatically

To select an item programmatically in a wx.ListCtrl (note that this appears to be a bug ? Shouldn't need to use wx.LIST_STATE_SELECTED for stateMask argument, should be able to use a MASK argument instead ?) :

It should be (I think) :

Note : I just tried both versions, and the first version works in wxPython 2.5 ; the second version (using LIST_MASK_STATE) does not.

I think only the first version is correct. The last parameter is a mask of all the states you want to modify, so it must consist only of wx.LIST_STATE_* combinations. The wx.LIST_MASK_STATE is only used in SetItem, where it tells which fields are valid. Seems the docs could be clearer though.

Retrieve Currently Selected Indices in List Control

A common task, there's no pre-built function to accomplish this, so here's a recipe:

   1 def _getSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
   2         indices = []
   3         lastFound = -1
   4         while True:
   5                 index = self.GetNextItem(
   6                         lastFound,
   7                         wxLIST_NEXT_ALL,
   8                         state,
   9                 )
  10                 if index == -1:
  11                         break
  12                 else:
  13                         lastFound = index
  14                         indices.append( index )
  15         return indices

wx.ListCtrl's Hello world (Phoenix)

It took half an hour for a newbie like me to get this tiny application running. Until I saw that you must call "InsertItem" :-) .

img_sample_one.png

   1 # sample_one.py
   2 
   3 import wx
   4 
   5 # class MyFrame
   6 # class MyApp
   7 
   8 #---------------------------------------------------------------------------
   9 
  10 data = [("World", "Python", "Welcome"),
  11         ("wxWidgets", "Data", "Items"),
  12         ("ListCtrl", "Report", "Border"),
  13         ("Index", "Column", "Insert"),
  14         ("Width", "Header", "Image")]
  15 
  16 #---------------------------------------------------------------------------
  17 
  18 class MyFrame(wx.Frame):
  19     def __init__(self):
  20         wx.Frame.__init__(self, None, -1,
  21                           "List control report",
  22                           size=(380, 220))
  23 
  24         id = wx.NewIdRef()
  25         self.list = wx.ListCtrl(self, id,
  26                                 style=wx.LC_REPORT|
  27                                       wx.SUNKEN_BORDER)
  28 
  29         # Add some columns
  30         self.list.InsertColumn(0, "Data #1")
  31         self.list.InsertColumn(1, "Data #2")
  32         self.list.InsertColumn(2, "Data #3")
  33 
  34         # Add the rows
  35         for item in data:
  36             index = self.list.InsertItem(self.list.GetItemCount(), item[0])
  37             for col, text in enumerate(item[1:]):
  38                 self.list.SetItem(index, col+1, text)
  39 
  40         # Set the width of the columns
  41         self.list.SetColumnWidth(0, 120)
  42         self.list.SetColumnWidth(1, 120)
  43         self.list.SetColumnWidth(2, 120)
  44 
  45 #---------------------------------------------------------------------------
  46 
  47 class MyApp(wx.App):
  48     def OnInit(self):
  49 
  50         #------------
  51 
  52         frame = MyFrame()
  53         self.SetTopWindow(frame)
  54         frame.Show(True)
  55 
  56         return True
  57 
  58 #---------------------------------------------------------------------------
  59 
  60 def main():
  61     app = MyApp(False)
  62     app.MainLoop()
  63 
  64 #---------------------------------------------------------------------------
  65 
  66 if __name__ == "__main__" :
  67     main()

Changing fonts in a ListCtrl (Phoenix)

Supposing you have a List Control, and you want to set some items to, say, bold. That's all - no changing anything else about the font, so the face remains the same as the other items. (Bear in mind the face will most likely be the default face as set by the system, and hence we don't know what it is.)

Because I (Dave Cridland) am terminally stupid, I didn't figure out how to do this, and couldn't find any documentation. In case anyone else is trying to do the same thing, and can't figure it out either, here's what I did:

img_sample_two.png

   1 # sample_two.py
   2 
   3 import wx
   4 
   5 # class MyFancyListCtrl
   6 # class MyFrame
   7 # class MyApp
   8 
   9 #---------------------------------------------------------------------------
  10 
  11 class MyFancyListCtrl(wx.ListCtrl):
  12     def __init__(self, parent, id):
  13         wx.ListCtrl.__init__(self, parent, id,
  14                              style=wx.LC_REPORT|
  15                                    wx.LC_VIRTUAL|
  16                                    wx.SUNKEN_BORDER)
  17 
  18         # Add some columns
  19         self.InsertColumn(0, "Data #1")
  20         self.InsertColumn(1, "Data #2")
  21         self.InsertColumn(2, "Data #3")
  22 
  23         # Set the width of the columns
  24         self.SetColumnWidth(0, 120)
  25         self.SetColumnWidth(1, 120)
  26         self.SetColumnWidth(2, 120)
  27 
  28         self.SetItemCount(10)
  29 
  30         # We setup our pretty attribute once, here.
  31         self._funky_attr = wx.ListItemAttr()
  32 
  33         # This now contains default attributes.
  34         # We can set the text colour to be different :
  35         self._funky_attr.SetTextColour(wx.BLUE)
  36 
  37         # But we can't do either of :
  38         # self._funky_attr.GetFont().SetWeight(wx.BOLD)
  39         # (Above fails silently - probably GetFont() returns a copy).
  40         # new_font = wx.Font()
  41         # (No default constructor in wxPython).
  42         # But we can extract the default font :
  43         new_font = self._funky_attr.GetFont()
  44 
  45         # Set the weight on it :
  46         new_font.SetWeight(wx.BOLD)
  47 
  48         # Then put it back.
  49         self._funky_attr.SetFont(new_font)
  50         # self._funky_attr is now ready to be returned by OnGetItemAttr()
  51         # (since this happens to be virtual).
  52 
  53         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  54         self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  55         self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
  56 
  57     #-----------------------------------------------------------------------
  58 
  59     def OnItemSelected(self, event):
  60         self.currentItem = event.Index
  61         print('OnItemSelected: "%s", "%s", "%s", "%s"\n' %
  62               (self.currentItem,
  63                self.GetItemText(self.currentItem),
  64                self.GetColumnText(self.currentItem, 1),
  65                self.GetColumnText(self.currentItem, 2)))
  66 
  67 
  68     def OnItemActivated(self, event):
  69         self.currentItem = event.Index
  70         print("OnItemActivated: %s\nTopItem: %s\n" %
  71               (self.GetItemText(self.currentItem), self.GetTopItem()))
  72 
  73 
  74     def OnItemDeselected(self, evt):
  75         print("OnItemDeselected: %s" % evt.Index)
  76 
  77 
  78     def GetColumnText(self, index, col):
  79         item = self.GetItem(index, col)
  80         return item.GetText()
  81 
  82 
  83     def OnGetItemText(self, item, col):
  84         return "Item %d, column %d" % (item, col)
  85 
  86 
  87     def OnGetItemAttr(self, item):
  88         if item % 2 == 1:
  89             return self._funky_attr
  90         else:
  91             return None
  92 
  93 #---------------------------------------------------------------------------
  94 
  95 class MyFrame(wx.Frame):
  96     def __init__(self):
  97         wx.Frame.__init__(self, None, -1,
  98                           "Fancy list control",
  99                           size=(400, 240))
 100 
 101         id = wx.NewIdRef()
 102         self.list = MyFancyListCtrl(self, id)
 103 
 104 #---------------------------------------------------------------------------
 105 
 106 class MyApp(wx.App):
 107     def OnInit(self):
 108 
 109         #------------
 110 
 111         frame = MyFrame()
 112         self.SetTopWindow(frame)
 113         frame.Show(True)
 114 
 115         return True
 116 
 117 #---------------------------------------------------------------------------
 118 
 119 def main():
 120     app = MyApp(False)
 121     app.MainLoop()
 122 
 123 #---------------------------------------------------------------------------
 124 
 125 if __name__ == "__main__" :
 126     main()

Simply changing the font of a specific item :

   1 # Get the item at a specific index :
   2 item = self.myListControl.GetItem(index)
   3 # Get its font, change it, and put it back :
   4 font = item.GetFont()
   5 font.SetWeight(wx.FONTWEIGHT_BOLD)
   6 item.SetFont(font)
   7 # This does the trick:
   8 self.myListControl.SetItem(item)

Unselecting an item programmatically (Phoenix)

It took me (Werner Bruhin) some searching, as always when one figures it out it is easy!

   1 # Selecting as shown in the demo
   2 self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
   3 
   4 # Unselecting
   5 self.SetItemState(item, 0, wx.LIST_STATE_SELECTED)

Type Ahead Mixin

Windows (and presumably other OS do as well) provides Type Ahead functionality by default in list controls. But not if they are Virtual. I had a need to provide Type Ahead for some virtual controls in my app, so I knocked up this Mixin class for wxListCtrl objects. Happily it works with both Virtual and Normal list controls which means if you use it in your app then all your list controls can have the same Type Ahead behaviour.

There are some things I've tried to make configurable; the type ahead timeout, case sensitivity to the search, special keycodes to avoid during typeahead, and I've provided methods that you could override to change the default behaviour that I've coded (it was almost on a whim as I didn't really like the behaviour that Windows was providing, it seemed, weird). To help understand what's going on I've tried to document the code to explain the bits I think are weird.

One thing that is notable is that the default windows type ahead doesn't seem to recognise the space character, with some playing about with EVT_KEY_DOWN and EVT_CHAR events I've made my type ahead deal with spaces. Which is nice.

Anyway, on with the code (please excuse the verbosity of my variable and method names :) ).

   1 from wxPython.wx import *
   2 
   3 class TypeAheadListCtrlMixin:
   4     """  A Mixin Class that does type ahead scrolling for list controls.
   5          Assumes that the wxListCtrl it is mixed into is sorted (it's using
   6          a binary search to find the correct item).
   7 
   8          I wrote this because on Windows there was no type ahead when you
   9          used a virtual list control, and then couldn't be bohered deciphering
  10          the default windows typeahead for non-virtual list controls.  So I
  11          made it work for both virtual and non-virtual controls so that all
  12          my list controls would have the same functionality.
  13 
  14          Things you can change programatically:
  15          * expand or contract the list of keycodes that stop the type ahead
  16          * expand or contract the list of keycodes that are allowed to be
  17            used inside typeahead, but won't start it (e.g. space which normally
  18            acts as an Activation Key)
  19          * change the timeout time (init param, defaults to 500 milliseconds)
  20          * change the sensitivity of the search (init param, defaults to caseinsensitive)
  21          Things you can change in the class that you mix this into:
  22          * override the following methods:
  23            - currentlySelectedItemFoundByTypeAhead
  24            - currentlySelectedItemNotFoundByTypeAhead
  25            - newItemFoundByTypeAhead
  26            - nothingFoundByTypeAhead
  27            changing these changes the behaviour of the typeahead in various stages.
  28            See doc comments on methods.
  29 
  30         Written by Murray Steele (muz at h-lame dot com)
  31     """
  32 
  33     # These Keycodes are the ones that if we detect them we will cancel the current
  34     # typeahead state.
  35     stopTypeAheadKeyCodes = [
  36      WXK_BACK,
  37      WXK_TAB,
  38      WXK_RETURN,
  39      WXK_ESCAPE,
  40      WXK_DELETE,
  41      WXK_START,
  42      WXK_LBUTTON,
  43      WXK_RBUTTON,
  44      WXK_CANCEL,
  45      WXK_MBUTTON,
  46      WXK_CLEAR,
  47      WXK_PAUSE,
  48      WXK_CAPITAL,
  49      WXK_PRIOR,
  50      WXK_NEXT,
  51      WXK_END,
  52      WXK_HOME,
  53      WXK_LEFT,
  54      WXK_UP,
  55      WXK_RIGHT,
  56      WXK_DOWN,
  57      WXK_SELECT,
  58      WXK_PRINT,
  59      WXK_EXECUTE,
  60      WXK_SNAPSHOT,
  61      WXK_INSERT,
  62      WXK_HELP,
  63      WXK_F1,
  64      WXK_F2,
  65      WXK_F3,
  66      WXK_F4,
  67      WXK_F5,
  68      WXK_F6,
  69      WXK_F7,
  70      WXK_F8,
  71      WXK_F9,
  72      WXK_F10,
  73      WXK_F11,
  74      WXK_F12,
  75      WXK_F13,
  76      WXK_F14,
  77      WXK_F15,
  78      WXK_F16,
  79      WXK_F17,
  80      WXK_F18,
  81      WXK_F19,
  82      WXK_F20,
  83      WXK_F21,
  84      WXK_F22,
  85      WXK_F23,
  86      WXK_F24,
  87      WXK_NUMLOCK,
  88      WXK_SCROLL]
  89     # These are the keycodes that we have to catch in evt_key_down, not evt_char
  90     # By the time they get to evt_char then the OS has looked at them and gone,
  91     # hey, this keypress means do something (like pressing space acts as an ACTIVATE
  92     # key in a list control.
  93     catchInKeyDownIfDuringTypeAheadKeyCodes = [
  94      WXK_SPACE
  95     ]
  96     # These are the keycodes that we will allow during typeahead, but won't allow to start
  97     # the type ahead process.
  98     dontStartTypeAheadKeyCodes = [
  99      WXK_SHIFT,
 100      WXK_CONTROL,
 101      WXK_MENU #ALT Key, ALT Gr generates both WXK_CONTROL and WXK_MENU.
 102      ]
 103     dontStartTypeAheadKeyCodes.extend(catchInKeyDownIfDuringTypeAheadKeyCodes)
 104 
 105     def __init__(self, typeAheadTimeout = 500, casesensitive = False, columnToSearch = 0):
 106         # Do most work in the char handler instead of keydown.
 107         # This means we get the correct keycode for the key pressed as it should
 108         # appear on screen, rather than all uppercase or "default" us keyboard
 109         # punctuation.
 110         # However there are things that we need to catch in key_down to stop
 111         # them getting sent to the underlying windows control and generating
 112         # other events (notably I'm talking about the SPACE key which generates
 113         # an ACTIVATE event in these list controls).
 114         EVT_KEY_DOWN(self, self.OnTypeAheadKeyDown)
 115         EVT_CHAR(self, self.OnTypeAheadChar)
 116         timerId = wxNewId()
 117         self.typeAheadTimer = wxTimer(self,timerId)
 118         EVT_TIMER(self,timerId,self.OnTypeAheadTimer)
 119         self.clearTypeAhead()
 120         self.typeAheadTimeout = typeAheadTimeout
 121         self.columnToSearch = columnToSearch
 122         if not casesensitive:
 123             self._GetItemText = lambda idx: self.GetItem(idx,self.columnToSearch).GetText().lower()
 124             self._GetKeyCode = lambda keycode: chr(keycode).lower()
 125         else:
 126             self._GetItemText = lambda idx: self.GetItem(idx,self.columnToSearch).GetText()
 127             self._GetKeyCode = chr
 128 
 129     def OnTypeAheadKeyDown(self, event):
 130         keycode = event.GetKeyCode()
 131         if keycode in self.stopTypeAheadKeyCodes:
 132             self.clearTypeAhead()
 133         elif self.typeAhead == None:
 134             if keycode in self.dontStartTypeAheadKeyCodes:
 135                 self.clearTypeAhead()
 136         else:
 137             if keycode in self.catchInKeyDownIfDuringTypeAheadKeyCodes:
 138                 self.OnTypeAheadChar(event)
 139                 return
 140         event.Skip()
 141 
 142     def OnTypeAheadChar(self, event):
 143         # stop the timer, to make sure that it doesn't fire in the middle of
 144         # doing this and screw up by None-ifying the typeAhead string.
 145         # TODO: Yes some kind of lock around a typeAheadState object
 146         # that contained typeAhead, lastTypeAheadFoundAnything and lastTypeAhead
 147         # would be better...
 148         self.typeAheadTimer.Stop()
 149         keycode = event.GetKeyCode()
 150         if keycode in self.stopTypeAheadKeyCodes:
 151             self.clearTypeAhead()
 152             event.Skip()
 153             return
 154         else:
 155             if self.typeAhead == None:
 156                 if keycode in self.dontStartTypeAheadKeyCodes:
 157                     self.clearTypeAhead()
 158                     event.Skip()
 159                     return
 160                 else:
 161                     self.typeAhead = self._GetKeyCode(keycode)
 162             else:
 163                 self.typeAhead += self._GetKeyCode(keycode)
 164             self.doTypeAhead()
 165             # This timer is used to nullify the typeahead after a while
 166             self.typeAheadTimer.Start(self.typeAheadTimeout,wxTIMER_ONE_SHOT)
 167 
 168     def inTypeAhead(self):
 169         return self.typeAhead != None
 170 
 171     def currentlySelectedItemFoundByTypeAhead(self, idx):
 172         """This method is called when the typeahead string matches
 173            the text of the currently selected item.  Put code here if
 174            you want to have something happen in this case.
 175            NOTE: Method only called if there was a currently selected item.
 176 
 177            idx refers to the index of the currently selected item."""
 178         # we don't do anything as we've already selected the thing we want
 179         pass
 180 
 181     def currentlySelectedItemNotFoundByTypeAhead(self, idx):
 182         """This method is called when the typeahead string matches
 183            an item that isn't the currently selected one.  Put code
 184            here if you want something to happen to the currently
 185            selected item.
 186            NOTE: use newItemFoundByTypeAhead for doing something to
 187            the newly matched item.
 188            NOTE: Method only called if there was a currently selected item.
 189 
 190            idx referes to the index of the currently selected item."""
 191         # we deselect it.
 192         self.SetItemState(idx, 0, wxLIST_STATE_SELECTED)
 193         self.SetItemState(idx, 0, wxLIST_STATE_FOCUSED)
 194 
 195     def newItemFoundByTypeAhead(self, idx):
 196         """This is called when the typeahead string matches
 197            an item that isn't the currently selected one.  Put
 198            code here if you want something to happen to the newly
 199            found item.
 200            NOTE: use currentlySelectedItemNotFoundByTypeAhead for
 201            doing something to the previously selected item.
 202 
 203            idx refers to the index of the newly matched item."""
 204         # we select it and make sure it is focused
 205         self.SetItemState(idx, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED)
 206         self.SetItemState(idx, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED)
 207         self.EnsureVisible(idx)
 208 
 209     def nothingFoundByTypeAhead(self, idx):
 210         """This method is called when the typeahead string doesn't
 211            match any items.  Put code here if you want something to
 212            happen in this case.
 213 
 214            idx refers to the index of the currently selected item
 215            or -1 if nothing was selected."""
 216         # don't do anything here, what could we do?
 217         pass
 218 
 219     def doTypeAhead(self):
 220         curselected = -1
 221         if self.lastTypeAheadFoundSomething:
 222             curselected = self.lastTypeAhead
 223         else:
 224             curselected = self.GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)
 225         min = 0
 226         if curselected != -1:
 227             term_name = self._GetItemText(curselected)
 228             if term_name.startswith(self.typeAhead):
 229                 self.currentlySelectedItemFoundByTypeAhead(curselected)
 230                 self.lastTypeAheadFoundAnything = True
 231                 self.lastTypeAhead = curselected
 232                 return #We don't want this edgecase falling through
 233 
 234         new_idx = self.binary_search(self.typeAhead,min)
 235         if new_idx != -1:
 236             if new_idx != curselected and curselected != -1:
 237                 self.currentlySelectedItemNotFoundByTypeAhead(curselected)
 238             self.newItemFoundByTypeAhead(new_idx)
 239             self.lastTypeAheadFoundAnything = True
 240             self.lastTypeAhead = new_idx
 241         else:
 242             self.nothingFoundByTypeAhead(curselected)
 243             self.lastTypeAheadFoundAnything = False
 244             self.lastTypeAhead = -1
 245 
 246     # NOTE: Originally from ASPN. Augmented.
 247     def binary_search(self, t, min = 0):
 248         min = min;
 249         max = self.GetItemCount() - 1
 250         while True:
 251             if max < min:
 252                 return self.doEdgeCase(m, t)
 253             m = (min + max) / 2
 254             cur_term = self._GetItemText(m)
 255             if cur_term < t:
 256                 min = m + 1
 257             elif cur_term > t:
 258                 max = m - 1
 259             else:
 260                 return m
 261 
 262     def doEdgeCase(self, m, t):
 263         """ This method makes sure that if we don't find the typeahead
 264          as an actual string, then we will return the first item
 265          that starts with the typeahead string (if there is one)"""
 266         before = self._GetItemText(max(0,m-1))
 267         this = self._GetItemText(m)
 268         after = self._GetItemText(min(self.GetItemCount()-1,m+1))
 269         if this.startswith(t):
 270             return m
 271         elif before.startswith(t):
 272             return max(0,m-1)
 273         elif after.startswith(t):
 274             return min(self.GetItemCount()-1,m+1)
 275         else:
 276             return -1
 277 
 278     def clearTypeAhead(self):
 279         self.typeAhead = None
 280         self.lastTypeAheadFoundSomething = False
 281         self.lastTypeAheadIdx = -1
 282 
 283     def OnTypeAheadTimer(self, event):
 284         self.clearTypeAhead()

Customizing ColumnSorterMixin to Sort Dates

This code augments wx.lib.mixins.listctrl.ColumnSorterMixin so that it can sort dates that match the date_re regular expression listed at the top of the code. You need to modify another section of the code to transform your date into the YYYYMMDD format so that the dates can be easily sorted numerically. Alternatively, you could use the datetime module and store and sort date objects.

   1 import wx
   2 import wx.lib.mixins.listctrl
   3 import locale
   4 import re
   5 
   6 # Change this to your settings
   7 date_re = re.compile("(\d{2})-(\d{2})-(\d{4})")
   8 
   9 #----------------------------------------------------------------------------
  10 
  11 class CustColumnSorterMixin(wx.lib.mixins.listctrl.ColumnSorterMixin):
  12     def __init__(self, numColumns):
  13         wx.lib.mixins.listctrl.ColumnSorterMixin(self, numColumns)
  14 
  15     def GetColumnSorter(self):
  16         return self.CustColumnSorter
  17 
  18     def CustColumnSorter(self, key1, key2):
  19         col = self._col
  20         ascending = self._colSortFlag[col]
  21         item1 = self.itemDataMap[key1][col]
  22         item2 = self.itemDataMap[key2][col]
  23 
  24         alpha = date_re.match(item1)
  25         beta =  date_re.match(item2)
  26         if alpha and beta:
  27             # Change these from your settings to YYYYMMDD
  28             item1 = alpha.group(3)+alpha.group(1)+alpha.group(2)
  29             item2 =  beta.group(3)+ beta.group(1)+ beta.group(2)
  30 
  31             item1 = int(item1)
  32             item2 = int(item2)
  33 
  34         #--- Internationalization of string sorting with locale module
  35         if type(item1) == type('') or type(item2) == type(''):
  36             cmpVal = locale.strcoll(str(item1), str(item2))
  37         else:
  38             cmpVal = cmp(item1, item2)
  39         #---
  40 
  41         # If the items are equal then pick something else to make the sort value unique
  42         if cmpVal == 0:
  43             cmpVal = cmp(*self.GetSecondarySortValues(col, key1, key2))
  44 
  45         if ascending:
  46             return cmpVal
  47         else:
  48             return -cmpVal

Drag and Drop with lists - 1

Here's how you can use drag-and-drop to reorder a simple list, or to move items from one list to another.

As it stands, item data will be lost. Maybe in version 2! - JohnFouhy

   1 """ DnD demo with listctrl. """
   2 
   3 import wx
   4 
   5 class DragList(wx.ListCtrl):
   6     def __init__(self, *arg, **kw):
   7         if 'style' in kw and (kw['style']&wx.LC_LIST or kw['style']&wx.LC_REPORT):
   8             kw['style'] |= wx.LC_SINGLE_SEL
   9         else:
  10             kw['style'] = wx.LC_SINGLE_SEL|wx.LC_LIST
  11 
  12         wx.ListCtrl.__init__(self, *arg, **kw)
  13 
  14         self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDrag)
  15 
  16         dt = ListDrop(self._insert)
  17         self.SetDropTarget(dt)
  18 
  19     def _startDrag(self, e):
  20         """ Put together a data object for drag-and-drop _from_ this list. """
  21 
  22         # Create the data object: Just use plain text.
  23         data = wx.PyTextDataObject()
  24         idx = e.GetIndex()
  25         text = self.GetItem(idx).GetText()
  26         data.SetText(text)
  27 
  28         # Create drop source and begin drag-and-drop.
  29         dropSource = wx.DropSource(self)
  30         dropSource.SetData(data)
  31         res = dropSource.DoDragDrop(flags=wx.Drag_DefaultMove)
  32 
  33         # If move, we want to remove the item from this list.
  34         if res == wx.DragMove:
  35             # It's possible we are dragging/dropping from this list to this list.  In which case, the
  36             # index we are removing may have changed...
  37 
  38             # Find correct position.
  39             pos = self.FindItem(idx, text)
  40             self.DeleteItem(pos)
  41 
  42     def _insert(self, x, y, text):
  43         """ Insert text at given x, y coordinates --- used with drag-and-drop. """
  44 
  45         # Clean text.
  46         import string
  47         text = filter(lambda x: x in (string.letters + string.digits + string.punctuation + ' '), text)
  48 
  49         # Find insertion point.
  50         index, flags = self.HitTest((x, y))
  51 
  52         if index == wx.NOT_FOUND:
  53             if flags & wx.LIST_HITTEST_NOWHERE:
  54                 index = self.GetItemCount()
  55             else:
  56                 return
  57 
  58         # Get bounding rectangle for the item the user is dropping over.
  59         rect = self.GetItemRect(index)
  60 
  61         # If the user is dropping into the lower half of the rect, we want to insert _after_ this item.
  62         if y > rect.y + rect.height/2:
  63             index += 1
  64 
  65         self.InsertStringItem(index, text)
  66 
  67 class ListDrop(wx.PyDropTarget):
  68     """ Drop target for simple lists. """
  69 
  70     def __init__(self, setFn):
  71         """ Arguments:
  72          - setFn: Function to call on drop.
  73         """
  74         wx.PyDropTarget.__init__(self)
  75 
  76         self.setFn = setFn
  77 
  78         # specify the type of data we will accept
  79         self.data = wx.PyTextDataObject()
  80         self.SetDataObject(self.data)
  81 
  82     # Called when OnDrop returns True.  We need to get the data and
  83     # do something with it.
  84     def OnData(self, x, y, d):
  85         # copy the data from the drag source to our data object
  86         if self.GetData():
  87             self.setFn(x, y, self.data.GetText())
  88 
  89         # what is returned signals the source what to do
  90         # with the original data (move, copy, etc.)  In this
  91         # case we just return the suggested value given to us.
  92         return d
  93 
  94 if __name__ == '__main__':
  95     items = ['Foo', 'Bar', 'Baz', 'Zif', 'Zaf', 'Zof']
  96 
  97     class MyApp(wx.App):
  98         def OnInit(self):
  99             self.frame = wx.Frame(None, title='Main Frame')
 100             self.frame.Show(True)
 101             self.SetTopWindow(self.frame)
 102             return True
 103 
 104     app = MyApp(redirect=False)
 105     dl1 = DragList(app.frame)
 106     dl2 = DragList(app.frame)
 107     sizer = wx.BoxSizer()
 108     app.frame.SetSizer(sizer)
 109     sizer.Add(dl1, proportion=1, flag=wx.EXPAND)
 110     sizer.Add(dl2, proportion=1, flag=wx.EXPAND)
 111     for item in items:
 112         dl1.InsertStringItem(99, item)
 113         dl2.InsertStringItem(99, item)
 114     app.frame.Layout()
 115     app.MainLoop()

The content on this page came from ListAndTreeControls, which was split up into this page and TreeControls .

How to create a list control (info) (last edited 2020-12-13 13:46:55 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.