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
22 # 13/10/2004 - Pim Van Heuven (pim@think-wize.com)
23 # o wxTextEditMixin: Support Horizontal scrolling when TAB is pressed on long
24 # ListCtrls, support for WXK_DOWN, WXK_UP, performance improvements on
25 # very long ListCtrls, Support for virtual ListCtrls
27 # 15-Oct-2004 - Robin Dunn
28 # o wxTextEditMixin: Added Shift-TAB support
34 #----------------------------------------------------------------------------
36 class ColumnSorterMixin
:
38 A mixin class that handles sorting of a wx.ListCtrl in REPORT mode when
39 the column header is clicked on.
41 There are a few requirments needed in order for this to work genericly:
43 1. The combined class must have a GetListCtrl method that
44 returns the wx.ListCtrl to be sorted, and the list control
45 must exist at the time the wx.ColumnSorterMixin.__init__
46 method is called because it uses GetListCtrl.
48 2. Items in the list control must have a unique data value set
49 with list.SetItemData.
51 3. The combined class must have an attribute named itemDataMap
52 that is a dictionary mapping the data values to a sequence of
53 objects representing the values in each column. These values
54 are compared in the column sorter to determine sort order.
56 Interesting methods to override are GetColumnSorter,
57 GetSecondarySortValues, and GetSortImages. See below for details.
60 def __init__(self
, numColumns
):
61 self
.SetColumnCount(numColumns
)
62 list = self
.GetListCtrl()
64 raise ValueError, "No wx.ListCtrl available"
65 self
.Bind(wx
.EVT_LIST_COL_CLICK
, self
.__OnColClick
, list)
68 def SetColumnCount(self
, newNumColumns
):
69 self
._colSortFlag
= [0] * newNumColumns
73 def SortListItems(self
, col
=-1, ascending
=1):
74 """Sort the list on demand. Can also be used to set the sort column and order."""
78 self
._colSortFlag
[col
] = ascending
79 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
80 self
.__updateImages
(oldCol
)
83 def GetColumnWidths(self
):
85 Returns a list of column widths. Can be used to help restore the current
88 list = self
.GetListCtrl()
90 for x
in range(len(self
._colSortFlag
)):
91 rv
.append(list.GetColumnWidth(x
))
95 def GetSortImages(self
):
97 Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column
98 header when sorting in descending order.
100 return (-1, -1) # (decending, ascending) image IDs
103 def GetColumnSorter(self
):
104 """Returns a callable object to be used for comparing column values when sorting."""
105 return self
.__ColumnSorter
108 def GetSecondarySortValues(self
, col
, key1
, key2
):
109 """Returns a tuple of 2 values to use for secondary sort values when the
110 items in the selected column match equal. The default just returns the
115 def __OnColClick(self
, evt
):
117 self
._col
= col
= evt
.GetColumn()
118 self
._colSortFlag
[col
] = not self
._colSortFlag
[col
]
119 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
120 self
.__updateImages
(oldCol
)
124 def __ColumnSorter(self
, key1
, key2
):
126 ascending
= self
._colSortFlag
[col
]
127 item1
= self
.itemDataMap
[key1
][col
]
128 item2
= self
.itemDataMap
[key2
][col
]
130 #--- Internationalization of string sorting with locale module
131 if type(item1
) == type('') or type(item2
) == type(''):
132 cmpVal
= locale
.strcoll(str(item1
), str(item2
))
134 cmpVal
= cmp(item1
, item2
)
137 # If the items are equal then pick something else to make the sort value unique
139 cmpVal
= apply(cmp, self
.GetSecondarySortValues(col
, key1
, key2
))
147 def __updateImages(self
, oldCol
):
148 sortImages
= self
.GetSortImages()
149 if self
._col
!= -1 and sortImages
[0] != -1:
150 img
= sortImages
[self
._colSortFlag
[self
._col
]]
151 list = self
.GetListCtrl()
153 list.ClearColumnImage(oldCol
)
154 list.SetColumnImage(self
._col
, img
)
157 #----------------------------------------------------------------------------
158 #----------------------------------------------------------------------------
160 class ListCtrlAutoWidthMixin
:
161 """ A mix-in class that automatically resizes the last column to take up
162 the remaining width of the wx.ListCtrl.
164 This causes the wx.ListCtrl to automatically take up the full width of
165 the list, without either a horizontal scroll bar (unless absolutely
166 necessary) or empty space to the right of the last column.
168 NOTE: This only works for report-style lists.
170 WARNING: If you override the EVT_SIZE event in your wx.ListCtrl, make
171 sure you call event.Skip() to ensure that the mixin's
172 _OnResize method is called.
174 This mix-in class was written by Erik Westra <ewestra@wave.co.nz>
177 """ Standard initialiser.
179 self
._resizeColMinWidth
= None
180 self
._resizeColStyle
= "LAST"
182 self
.Bind(wx
.EVT_SIZE
, self
._onResize
)
183 self
.Bind(wx
.EVT_LIST_COL_END_DRAG
, self
._onResize
, self
)
186 def setResizeColumn(self
, col
):
188 Specify which column that should be autosized. Pass either
189 'LAST' or the column number. Default is 'LAST'.
192 self
._resizeColStyle
= "LAST"
194 self
._resizeColStyle
= "COL"
195 self
._resizeCol
= col
198 def resizeLastColumn(self
, minWidth
):
199 """ Resize the last column appropriately.
201 If the list's columns are too wide to fit within the window, we use
202 a horizontal scrollbar. Otherwise, we expand the right-most column
203 to take up the remaining free space in the list.
205 This method is called automatically when the wx.ListCtrl is resized;
206 you can also call it yourself whenever you want the last column to
207 be resized appropriately (eg, when adding, removing or resizing
210 'minWidth' is the preferred minimum width for the last column.
212 self
.resizeCloumn(self
, minWidth
)
215 def resizeColumn(self
, minWidth
):
216 self
._resizeColMinWidth
= minWidth
220 # =====================
221 # == Private Methods ==
222 # =====================
224 def _onResize(self
, event
):
225 """ Respond to the wx.ListCtrl being resized.
227 We automatically resize the last column in the list.
229 wx
.CallAfter(self
._doResize
)
234 """ Resize the last column as appropriate.
236 If the list's columns are too wide to fit within the window, we use
237 a horizontal scrollbar. Otherwise, we expand the right-most column
238 to take up the remaining free space in the list.
240 We remember the current size of the last column, before resizing,
241 as the preferred minimum width if we haven't previously been given
242 or calculated a minimum width. This ensure that repeated calls to
243 _doResize() don't cause the last column to size itself too large.
246 if not self
: # avoid a PyDeadObject error
249 numCols
= self
.GetColumnCount()
250 if numCols
== 0: return # Nothing to resize.
252 if(self
._resizeColStyle
== "LAST"):
253 resizeCol
= self
.GetColumnCount()
255 resizeCol
= self
._resizeCol
257 if self
._resizeColMinWidth
== None:
258 self
._resizeColMinWidth
= self
.GetColumnWidth(resizeCol
- 1)
260 # We're showing the vertical scrollbar -> allow for scrollbar width
261 # NOTE: on GTK, the scrollbar is included in the client size, but on
262 # Windows it is not included
263 listWidth
= self
.GetClientSize().width
264 if wx
.Platform
!= '__WXMSW__':
265 if self
.GetItemCount() > self
.GetCountPerPage():
266 scrollWidth
= wx
.SystemSettings_GetMetric(wx
.SYS_VSCROLL_X
)
267 listWidth
= listWidth
- scrollWidth
269 totColWidth
= 0 # Width of all columns except last one.
270 for col
in range(numCols
):
271 if col
!= (resizeCol
-1):
272 totColWidth
= totColWidth
+ self
.GetColumnWidth(col
)
274 resizeColWidth
= self
.GetColumnWidth(resizeCol
- 1)
276 if totColWidth
+ self
._resizeColMinWidth
> listWidth
:
277 # We haven't got the width to show the last column at its minimum
278 # width -> set it to its minimum width and allow the horizontal
280 self
.SetColumnWidth(resizeCol
-1, self
._resizeColMinWidth
)
283 # Resize the last column to take up the remaining available space.
285 self
.SetColumnWidth(resizeCol
-1, listWidth
- totColWidth
)
290 #----------------------------------------------------------------------------
292 SEL_FOC
= wx
.LIST_STATE_SELECTED | wx
.LIST_STATE_FOCUSED
293 def selectBeforePopup(event
):
294 """Ensures the item the mouse is pointing at is selected before a popup.
296 Works with both single-select and multi-select lists."""
297 ctrl
= event
.GetEventObject()
298 if isinstance(ctrl
, wx
.ListCtrl
):
299 n
, flags
= ctrl
.HitTest(event
.GetPosition())
301 if not ctrl
.GetItemState(n
, wx
.LIST_STATE_SELECTED
):
302 for i
in range(ctrl
.GetItemCount()):
303 ctrl
.SetItemState(i
, 0, SEL_FOC
)
304 #for i in getListCtrlSelection(ctrl, SEL_FOC):
305 # ctrl.SetItemState(i, 0, SEL_FOC)
306 ctrl
.SetItemState(n
, SEL_FOC
, SEL_FOC
)
309 def getListCtrlSelection(listctrl
, state
=wx
.LIST_STATE_SELECTED
):
310 """ Returns list of item indexes of given state (selected by defaults) """
314 idx
= listctrl
.GetNextItem(idx
, wx
.LIST_NEXT_ALL
, state
)
320 wxEVT_DOPOPUPMENU
= wx
.NewEventType()
321 EVT_DOPOPUPMENU
= wx
.PyEventBinder(wxEVT_DOPOPUPMENU
, 0)
324 class ListCtrlSelectionManagerMix
:
325 """Mixin that defines a platform independent selection policy
327 As selection single and multi-select list return the item index or a
328 list of item indexes respectively.
333 self
.Bind(wx
.EVT_RIGHT_DOWN
, self
.OnLCSMRightDown
)
334 self
.Bind(EVT_DOPOPUPMENU
, self
.OnLCSMDoPopup
)
335 # self.Connect(-1, -1, self.wxEVT_DOPOPUPMENU, self.OnLCSMDoPopup)
338 def getPopupMenu(self
):
339 """ Override to implement dynamic menus (create) """
343 def setPopupMenu(self
, menu
):
344 """ Must be set for default behaviour """
348 def afterPopupMenu(self
, menu
):
349 """ Override to implement dynamic menus (destroy) """
353 def getSelection(self
):
354 res
= getListCtrlSelection(self
)
355 if self
.GetWindowStyleFlag() & wx
.LC_SINGLE_SEL
:
364 def OnLCSMRightDown(self
, event
):
365 selectBeforePopup(event
)
367 menu
= self
.getPopupMenu()
370 evt
.SetEventType(wxEVT_DOPOPUPMENU
)
372 evt
.pos
= event
.GetPosition()
373 wx
.PostEvent(self
, evt
)
376 def OnLCSMDoPopup(self
, event
):
377 self
.PopupMenu(event
.menu
, event
.pos
)
378 self
.afterPopupMenu(event
.menu
)
381 #----------------------------------------------------------------------------
382 from bisect
import bisect
387 A mixin class that handles enables any text in any column of a
388 multi-column listctrl to be edited by clicking on the given row
389 and column. You close the text editor by hitting the ENTER key or
390 clicking somewhere else on the listctrl. You switch to the next
391 column by hiting TAB.
393 To use the mixin you have to include it in the class definition
394 and call the __init__ function::
396 class TestListCtrl(wx.ListCtrl, TextEdit):
397 def __init__(self, parent, ID, pos=wx.DefaultPosition,
398 size=wx.DefaultSize, style=0):
399 wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
400 TextEdit.__init__(self)
403 Authors: Steve Zatz, Pim Van Heuven (pim@think-wize.com)
407 #editor = wx.TextCtrl(self, -1, pos=(-1,-1), size=(-1,-1),
408 # style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB \
412 self
.Bind(wx
.EVT_TEXT_ENTER
, self
.CloseEditor
)
413 self
.Bind(wx
.EVT_LEFT_DOWN
, self
.OnLeftDown
)
414 self
.Bind(wx
.EVT_LEFT_DCLICK
, self
.OnLeftDown
)
415 self
.Bind(wx
.EVT_LIST_ITEM_SELECTED
, self
.OnItemSelected
)
418 def make_editor(self
, col_style
=wx
.LIST_FORMAT_LEFT
):
419 editor
= wx
.PreTextCtrl()
421 style
=wx
.TE_PROCESS_ENTER|wx
.TE_PROCESS_TAB|wx
.TE_RICH2
422 style |
= {wx
.LIST_FORMAT_LEFT
: wx
.TE_LEFT
,
423 wx
.LIST_FORMAT_RIGHT
: wx
.TE_RIGHT
,
424 wx
.LIST_FORMAT_CENTRE
: wx
.TE_CENTRE
427 editor
.Create(self
, -1, style
=style
)
428 editor
.SetBackgroundColour(wx
.Colour(red
=255,green
=255,blue
=175)) #Yellow
429 font
= self
.GetFont()
438 self
.col_style
= col_style
439 self
.editor
.Bind(wx
.EVT_CHAR
, self
.OnChar
)
440 self
.editor
.Bind(wx
.EVT_KILL_FOCUS
, self
.CloseEditor
)
443 def OnItemSelected(self
, evt
):
444 self
.curRow
= evt
.GetIndex()
448 def OnChar(self
, event
):
449 ''' Catch the TAB, Shift-TAB, cursor DOWN/UP key code
450 so we can open the editor at the next column (if any).'''
452 keycode
= event
.GetKeyCode()
453 if keycode
== wx
.WXK_TAB
and event
.ShiftDown():
455 if self
.curCol
-1 >= 0:
456 self
.OpenEditor(self
.curCol
-1, self
.curRow
)
458 elif keycode
== wx
.WXK_TAB
:
460 if self
.curCol
+1 < self
.GetColumnCount():
461 self
.OpenEditor(self
.curCol
+1, self
.curRow
)
463 elif keycode
== wx
.WXK_ESCAPE
:
466 elif keycode
== wx
.WXK_DOWN
:
468 if self
.curRow
+1 < self
.GetItemCount():
469 self
._SelectIndex
(self
.curRow
+1)
470 self
.OpenEditor(self
.curCol
, self
.curRow
)
472 elif keycode
== wx
.WXK_UP
:
475 self
._SelectIndex
(self
.curRow
-1)
476 self
.OpenEditor(self
.curCol
, self
.curRow
)
482 def OnLeftDown(self
, evt
=None):
483 ''' Examine the click and double
484 click events to see if a row has been click on twice. If so,
485 determine the current row and columnn and open the editor.'''
487 if self
.editor
.IsShown():
490 x
,y
= evt
.GetPosition()
491 row
,flags
= self
.HitTest((x
,y
))
493 if row
!= self
.curRow
: # self.curRow keeps track of the current row
497 # the following should really be done in the mixin's init but
498 # the wx.ListCtrl demo creates the columns after creating the
499 # ListCtrl (generally not a good idea) on the other hand,
500 # doing this here handles adjustable column widths
504 for n
in range(self
.GetColumnCount()):
505 loc
= loc
+ self
.GetColumnWidth(n
)
506 self
.col_locs
.append(loc
)
509 col
= bisect(self
.col_locs
, x
+self
.GetScrollPos(wx
.HORIZONTAL
)) - 1
510 self
.OpenEditor(col
, row
)
513 def OpenEditor(self
, col
, row
):
514 ''' Opens an editor at the current position. '''
516 if self
.GetColumn(col
).m_format
!= self
.col_style
:
517 self
.make_editor(self
.GetColumn(col
).m_format
)
519 x0
= self
.col_locs
[col
]
520 x1
= self
.col_locs
[col
+1] - x0
522 scrolloffset
= self
.GetScrollPos(wx
.HORIZONTAL
)
525 if x0
+x1
-scrolloffset
> self
.GetSize()[0]:
526 if wx
.Platform
== "__WXMSW__":
527 # don't start scrolling unless we really need to
528 offset
= x0
+x1
-self
.GetSize()[0]-scrolloffset
529 # scroll a bit more than what is minimum required
530 # so we don't have to scroll everytime the user presses TAB
531 # which is very tireing to the eye
532 addoffset
= self
.GetSize()[0]/4
533 # but be careful at the end of the list
534 if addoffset
+ scrolloffset
< self
.GetSize()[0]:
537 self
.ScrollList(offset
, 0)
538 scrolloffset
= self
.GetScrollPos(wx
.HORIZONTAL
)
540 # Since we can not programmatically scroll the ListCtrl
541 # close the editor so the user can scroll and open the editor
543 self
.editor
.SetValue(self
.GetItem(row
, col
).GetText())
549 y0
= self
.GetItemRect(row
)[1]
552 editor
.SetDimensions(x0
-scrolloffset
,y0
, x1
,-1)
554 editor
.SetValue(self
.GetItem(row
, col
).GetText())
557 editor
.SetSelection(-1,-1)
564 def CloseEditor(self
, evt
=None):
565 ''' Close the editor and save the new value to the ListCtrl. '''
566 text
= self
.editor
.GetValue()
569 # replace by whather you use to populate the virtual ListCtrl
571 self
.SetVirtualData(self
.curRow
, self
.curCol
, text
)
573 self
.SetStringItem(self
.curRow
, self
.curCol
, text
)
574 self
.RefreshItem(self
.curRow
)
576 def _SelectIndex(self
, row
):
577 listlen
= self
.GetItemCount()
578 if row
< 0 and not listlen
:
580 if row
> (listlen
-1):
583 self
.SetItemState(self
.curRow
, ~wx
.LIST_STATE_SELECTED
,
584 wx
.LIST_STATE_SELECTED
)
585 self
.EnsureVisible(row
)
586 self
.SetItemState(row
, wx
.LIST_STATE_SELECTED
,
587 wx
.LIST_STATE_SELECTED
)
591 #----------------------------------------------------------------------------