1 #---------------------------------------------------------------------------- 
   2 # Name:        wxPython.lib.mixins.listctrl 
   3 # Purpose:     Helpful mix-in classes for wxListCtrl 
   9 # Copyright:   (c) 2001 by Total Control Software 
  10 # Licence:     wxWindows license 
  11 #---------------------------------------------------------------------------- 
  12 # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) 
  14 # o 2.5 compatability update. 
  15 # o ListCtrlSelectionManagerMix untested. 
  17 # 12/21/2003 - Jeff Grimmett (grimmtooth@softhome.net) 
  19 # o wxColumnSorterMixin -> ColumnSorterMixin  
  20 # o wxListCtrlAutoWidthMixin -> ListCtrlAutoWidthMixin  
  26 #---------------------------------------------------------------------------- 
  28 class ColumnSorterMixin
: 
  30     A mixin class that handles sorting of a wx.ListCtrl in REPORT mode when 
  31     the column header is clicked on. 
  33     There are a few requirments needed in order for this to work genericly: 
  35       1. The combined class must have a GetListCtrl method that 
  36          returns the wx.ListCtrl to be sorted, and the list control 
  37          must exist at the time the wx.ColumnSorterMixin.__init__ 
  38          method is called because it uses GetListCtrl. 
  40       2. Items in the list control must have a unique data value set 
  41          with list.SetItemData. 
  43       3. The combined class must have an attribute named itemDataMap 
  44          that is a dictionary mapping the data values to a sequence of 
  45          objects representing the values in each column.  These values 
  46          are compared in the column sorter to determine sort order. 
  48     Interesting methods to override are GetColumnSorter, 
  49     GetSecondarySortValues, and GetSortImages.  See below for details. 
  52     def __init__(self
, numColumns
): 
  53         self
.SetColumnCount(numColumns
) 
  54         list = self
.GetListCtrl() 
  56             raise ValueError, "No wx.ListCtrl available" 
  57         self
.Bind(wx
.EVT_LIST_COL_CLICK
, self
.__OnColClick
, list) 
  60     def SetColumnCount(self
, newNumColumns
): 
  61         self
._colSortFlag 
= [0] * newNumColumns
 
  65     def SortListItems(self
, col
=-1, ascending
=1): 
  66         """Sort the list on demand.  Can also be used to set the sort column and order.""" 
  70             self
._colSortFlag
[col
] = ascending
 
  71         self
.GetListCtrl().SortItems(self
.GetColumnSorter()) 
  72         self
.__updateImages
(oldCol
) 
  75     def GetColumnWidths(self
): 
  77         Returns a list of column widths.  Can be used to help restore the current 
  80         list = self
.GetListCtrl() 
  82         for x 
in range(len(self
._colSortFlag
)): 
  83             rv
.append(list.GetColumnWidth(x
)) 
  87     def GetSortImages(self
): 
  89         Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column 
  90         header when sorting in descending order. 
  92         return (-1, -1)  # (decending, ascending) image IDs 
  95     def GetColumnSorter(self
): 
  96         """Returns a callable object to be used for comparing column values when sorting.""" 
  97         return self
.__ColumnSorter
 
 100     def GetSecondarySortValues(self
, col
, key1
, key2
): 
 101         """Returns a tuple of 2 values to use for secondary sort values when the 
 102            items in the selected column match equal.  The default just returns the 
 107     def __OnColClick(self
, evt
): 
 109         self
._col 
= col 
= evt
.GetColumn() 
 110         self
._colSortFlag
[col
] = not self
._colSortFlag
[col
] 
 111         self
.GetListCtrl().SortItems(self
.GetColumnSorter()) 
 112         self
.__updateImages
(oldCol
) 
 116     def __ColumnSorter(self
, key1
, key2
): 
 118         ascending 
= self
._colSortFlag
[col
] 
 119         item1 
= self
.itemDataMap
[key1
][col
] 
 120         item2 
= self
.itemDataMap
[key2
][col
] 
 122         #--- Internationalization of string sorting with locale module 
 123         if type(item1
) == type('') or type(item2
) == type(''): 
 124             cmpVal 
= locale
.strcoll(str(item1
), str(item2
)) 
 126             cmpVal 
= cmp(item1
, item2
) 
 129         # If the items are equal then pick something else to make the sort value unique 
 131             cmpVal 
= apply(cmp, self
.GetSecondarySortValues(col
, key1
, key2
)) 
 139     def __updateImages(self
, oldCol
): 
 140         sortImages 
= self
.GetSortImages() 
 141         if self
._col 
!= -1 and sortImages
[0] != -1: 
 142             img 
= sortImages
[self
._colSortFlag
[self
._col
]] 
 143             list = self
.GetListCtrl() 
 145                 list.ClearColumnImage(oldCol
) 
 146             list.SetColumnImage(self
._col
, img
) 
 149 #---------------------------------------------------------------------------- 
 150 #---------------------------------------------------------------------------- 
 152 class ListCtrlAutoWidthMixin
: 
 153     """ A mix-in class that automatically resizes the last column to take up 
 154         the remaining width of the wx.ListCtrl. 
 156         This causes the wx.ListCtrl to automatically take up the full width of 
 157         the list, without either a horizontal scroll bar (unless absolutely 
 158         necessary) or empty space to the right of the last column. 
 160         NOTE:    This only works for report-style lists. 
 162         WARNING: If you override the EVT_SIZE event in your wx.ListCtrl, make 
 163                  sure you call event.Skip() to ensure that the mixin's 
 164                  _OnResize method is called. 
 166         This mix-in class was written by Erik Westra <ewestra@wave.co.nz> 
 169         """ Standard initialiser. 
 171         self
._lastColMinWidth 
= None 
 173         self
.Bind(wx
.EVT_SIZE
, self
._onResize
) 
 174         self
.Bind(wx
.EVT_LIST_COL_END_DRAG
, self
._onResize
, self
) 
 177     def resizeLastColumn(self
, minWidth
): 
 178         """ Resize the last column appropriately. 
 180             If the list's columns are too wide to fit within the window, we use 
 181             a horizontal scrollbar.  Otherwise, we expand the right-most column 
 182             to take up the remaining free space in the list. 
 184             This method is called automatically when the wx.ListCtrl is resized; 
 185             you can also call it yourself whenever you want the last column to 
 186             be resized appropriately (eg, when adding, removing or resizing 
 189             'minWidth' is the preferred minimum width for the last column. 
 191         self
._lastColMinWidth 
= minWidth
 
 194     # ===================== 
 195     # == Private Methods == 
 196     # ===================== 
 198     def _onResize(self
, event
): 
 199         """ Respond to the wx.ListCtrl being resized. 
 201             We automatically resize the last column in the list. 
 203         wx
.CallAfter(self
._doResize
) 
 208         """ Resize the last column as appropriate. 
 210             If the list's columns are too wide to fit within the window, we use 
 211             a horizontal scrollbar.  Otherwise, we expand the right-most column 
 212             to take up the remaining free space in the list. 
 214             We remember the current size of the last column, before resizing, 
 215             as the preferred minimum width if we haven't previously been given 
 216             or calculated a minimum width.  This ensure that repeated calls to 
 217             _doResize() don't cause the last column to size itself too large. 
 219         numCols 
= self
.GetColumnCount() 
 220         if numCols 
== 0: return # Nothing to resize. 
 222         if self
._lastColMinWidth 
== None: 
 223             self
._lastColMinWidth 
= self
.GetColumnWidth(numCols 
- 1) 
 225         # We're showing the vertical scrollbar -> allow for scrollbar width 
 226         # NOTE: on GTK, the scrollbar is included in the client size, but on 
 227         # Windows it is not included 
 228         listWidth 
= self
.GetClientSize().width
 
 229         if wx
.Platform 
!= '__WXMSW__': 
 230             if self
.GetItemCount() > self
.GetCountPerPage(): 
 231                 scrollWidth 
= wx
.SystemSettings_GetMetric(wx
.SYS_VSCROLL_X
) 
 232                 listWidth 
= listWidth 
- scrollWidth
 
 234         totColWidth 
= 0 # Width of all columns except last one. 
 235         for col 
in range(numCols
-1): 
 236             totColWidth 
= totColWidth 
+ self
.GetColumnWidth(col
) 
 238         lastColWidth 
= self
.GetColumnWidth(numCols 
- 1) 
 240         if totColWidth 
+ self
._lastColMinWidth 
> listWidth
: 
 241             # We haven't got the width to show the last column at its minimum 
 242             # width -> set it to its minimum width and allow the horizontal 
 244             self
.SetColumnWidth(numCols
-1, self
._lastColMinWidth
) 
 247         # Resize the last column to take up the remaining available space. 
 249         self
.SetColumnWidth(numCols
-1, listWidth 
- totColWidth
) 
 253 #---------------------------------------------------------------------------- 
 255 SEL_FOC 
= wx
.LIST_STATE_SELECTED | wx
.LIST_STATE_FOCUSED
 
 256 def selectBeforePopup(event
): 
 257     """Ensures the item the mouse is pointing at is selected before a popup. 
 259     Works with both single-select and multi-select lists.""" 
 260     ctrl 
= event
.GetEventObject() 
 261     if isinstance(ctrl
, wxListCtrl
): 
 262         n
, flags 
= ctrl
.HitTest(event
.GetPosition()) 
 264             if not ctrl
.GetItemState(n
, wx
.LIST_STATE_SELECTED
): 
 265                 for i 
in range(ctrl
.GetItemCount()): 
 266                     ctrl
.SetItemState(i
, 0, SEL_FOC
) 
 267                 #for i in getListCtrlSelection(ctrl, SEL_FOC): 
 268                 #    ctrl.SetItemState(i, 0, SEL_FOC) 
 269                 ctrl
.SetItemState(n
, SEL_FOC
, SEL_FOC
) 
 272 def getListCtrlSelection(listctrl
, state
=wx
.LIST_STATE_SELECTED
): 
 273     """ Returns list of item indexes of given state (selected by defaults) """ 
 277         idx 
= listctrl
.GetNextItem(idx
, wx
.LIST_NEXT_ALL
, state
) 
 283 wxEVT_DOPOPUPMENU 
= wx
.NewEventType() 
 284 EVT_DOPOPUPMENU 
= wx
.PyEventBinder(wxEVT_DOPOPUPMENU
, 0) 
 287 class ListCtrlSelectionManagerMix
: 
 288     """Mixin that defines a platform independent selection policy 
 290     As selection single and multi-select list return the item index or a 
 291     list of item indexes respectively. 
 296         self
.Bind(wx
.EVT_RIGHT_DOWN
, self
.OnLCSMRightDown
) 
 297         self
.Bind(EVT_DOPOPUPMENU
, self
.OnLCSMDoPopup
) 
 298 #        self.Connect(-1, -1, self.wxEVT_DOPOPUPMENU, self.OnLCSMDoPopup) 
 301     def getPopupMenu(self
): 
 302         """ Override to implement dynamic menus (create) """ 
 306     def setPopupMenu(self
, menu
): 
 307         """ Must be set for default behaviour """ 
 311     def afterPopupMenu(self
, menu
): 
 312         """ Override to implement dynamic menus (destroy) """ 
 316     def getSelection(self
): 
 317         res 
= getListCtrlSelection(self
) 
 318         if self
.GetWindowStyleFlag() & wx
.LC_SINGLE_SEL
: 
 327     def OnLCSMRightDown(self
, event
): 
 328         selectBeforePopup(event
) 
 330         menu 
= self
.getPopupMenu() 
 333             evt
.SetEventType(wxEVT_DOPOPUPMENU
) 
 335             evt
.pos 
= event
.GetPosition() 
 336             wx
.PostEvent(self
, evt
) 
 339     def OnLCSMDoPopup(self
, event
): 
 340         self
.PopupMenu(event
.menu
, event
.pos
) 
 341         self
.afterPopupMenu(event
.menu
) 
 344 #---------------------------------------------------------------------------- 
 345 from bisect 
import bisect
 
 350     A mixin class that handles enables any text in any column of a 
 351     multi-column listctrl to be edited by clicking on the given row 
 352     and column.  You close the text editor by hitting the ENTER key or 
 353     clicking somewhere else on the listctrl. You switch to the next 
 354     column by hiting TAB. 
 356     To use the mixin you have to include it in the class definition 
 357     and call the __init__ function:: 
 359         class TestListCtrl(wx.ListCtrl, TextEdit): 
 360             def __init__(self, parent, ID, pos=wx.DefaultPosition, 
 361                          size=wx.DefaultSize, style=0): 
 362                 wx.ListCtrl.__init__(self, parent, ID, pos, size, style) 
 363                 TextEdit.__init__(self)  
 366     Authors:     Steve Zatz, Pim Van Heuven (pim@think-wize.com) 
 370         #editor = wx.TextCtrl(self, -1, pos=(-1,-1), size=(-1,-1), 
 371         #                     style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB \ 
 373         editor 
= wx
.PreTextCtrl() 
 375         editor
.Create(self
, -1, style
=wx
.TE_PROCESS_ENTER|wx
.TE_PROCESS_TAB|wx
.TE_RICH2
) 
 376         editor
.SetBackgroundColour(wx
.Colour(red
=255,green
=255,blue
=175)) #Yellow 
 377         font 
= self
.GetFont() 
 381         self
.Bind(wx
.EVT_TEXT_ENTER
, self
.CloseEditor
) 
 382         self
.editor
.Bind(wx
.EVT_CHAR
, self
.OnChar
) 
 383         self
.editor
.Bind(wx
.EVT_KILL_FOCUS
, self
.CloseEditor
) 
 384         self
.Bind(wx
.EVT_LEFT_DOWN
, self
.OnLeftDown
) 
 385         self
.Bind(wx
.EVT_LEFT_DCLICK
, self
.OnLeftDown
) 
 386         self
.Bind(wx
.EVT_LIST_ITEM_SELECTED
, self
.OnItemSelected
) 
 390     def OnItemSelected(self
, evt
): 
 391         self
.curRow 
= evt
.GetIndex() 
 395     def OnChar(self
, event
): 
 396         ''' Catch the TAB key code so we can open the editor at the next column (if any).''' 
 397         if event
.GetKeyCode() == wx
.WXK_TAB
: 
 399             if self
.curCol
+1 < self
.GetColumnCount(): 
 400                 self
.OpenEditor(self
.curCol
+1, self
.curRow
) 
 405     def OnLeftDown(self
, evt
=None): 
 406         ''' Examine the click and double 
 407         click events to see if a row has been click on twice. If so, 
 408         determine the current row and columnn and open the editor.''' 
 410         if self
.editor
.IsShown(): 
 413         x
,y 
= evt
.GetPosition() 
 414         row
,flags 
= self
.HitTest((x
,y
)) 
 416         if row 
!= self
.curRow
: # self.curRow keeps track of the current row 
 420         # the following should really be done in the mixin's init but 
 421         # the wx.ListCtrl demo creates the columns after creating the 
 422         # ListCtrl (generally not a good idea) on the other hand, 
 423         # doing this here handles adjustable column widths 
 427         for n 
in range(self
.GetColumnCount()): 
 428             loc 
= loc 
+ self
.GetColumnWidth(n
) 
 429             self
.col_locs
.append(loc
) 
 431         col 
= bisect(self
.col_locs
, x
) - 1 
 432         self
.OpenEditor(col
, row
) 
 435     def OpenEditor(self
, col
, row
): 
 436         ''' Opens an editor at the current position. ''' 
 438         x0 
= self
.col_locs
[col
] 
 439         x1 
= self
.col_locs
[col
+1] - x0
 
 441         y0 
= self
.GetItemRect(row
)[1] 
 444         editor
.SetDimensions(x0
,y0
, x1
,-1) 
 445         editor
.SetValue(self
.GetItem(row
, col
).GetText())  
 448         editor
.SetSelection(-1,-1) 
 455     def CloseEditor(self
, evt
=None): 
 456         ''' Close the editor and save the new value to the ListCtrl. ''' 
 457         text 
= self
.editor
.GetValue() 
 459         self
.SetStringItem(self
.curRow
, self
.curCol
, text
) 
 463 #----------------------------------------------------------------------------