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 #----------------------------------------------------------------------------
13 from wxPython
.wx
import *
16 #----------------------------------------------------------------------------
18 class wxColumnSorterMixin
:
20 A mixin class that handles sorting of a wxListCtrl in REPORT mode when
21 the column header is clicked on.
23 There are a few requirments needed in order for this to work genericly:
25 1. The combined class must have a GetListCtrl method that
26 returns the wxListCtrl to be sorted, and the list control
27 must exist at the time the wxColumnSorterMixin.__init__
28 method is called because it uses GetListCtrl.
30 2. Items in the list control must have a unique data value set
31 with list.SetItemData.
33 3. The combined class must have an attribute named itemDataMap
34 that is a dictionary mapping the data values to a sequence of
35 objects representing the values in each column. These values
36 are compared in the column sorter to determine sort order.
38 Interesting methods to override are GetColumnSorter,
39 GetSecondarySortValues, and GetSortImages. See below for details.
42 def __init__(self
, numColumns
):
43 self
._colSortFlag
= [0] * numColumns
46 list = self
.GetListCtrl()
48 raise ValueError, "No wxListCtrl available"
49 EVT_LIST_COL_CLICK(list, list.GetId(), self
.__OnColClick
)
52 def SortListItems(self
, col
=-1, ascending
=1):
53 """Sort the list on demand. Can also be used to set the sort column and order."""
57 self
._colSortFlag
[col
] = ascending
58 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
59 self
.__updateImages
(oldCol
)
62 def GetColumnWidths(self
):
64 Returns a list of column widths. Can be used to help restore the current
67 list = self
.GetListCtrl()
69 for x
in range(len(self
._colSortFlag
)):
70 rv
.append(list.GetColumnWidth(x
))
74 def GetSortImages(self
):
76 Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column
77 header when sorting in descending order.
79 return (-1, -1) # (decending, ascending) image IDs
82 def GetColumnSorter(self
):
83 """Returns a callable object to be used for comparing column values when sorting."""
84 return self
.__ColumnSorter
87 def GetSecondarySortValues(self
, col
, key1
, key2
):
88 """Returns a tuple of 2 values to use for secondary sort values when the
89 items in the selected column match equal. The default just returns the
94 def __OnColClick(self
, evt
):
96 self
._col
= col
= evt
.GetColumn()
97 self
._colSortFlag
[col
] = not self
._colSortFlag
[col
]
98 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
99 self
.__updateImages
(oldCol
)
103 def __ColumnSorter(self
, key1
, key2
):
105 ascending
= self
._colSortFlag
[col
]
106 item1
= self
.itemDataMap
[key1
][col
]
107 item2
= self
.itemDataMap
[key2
][col
]
109 #--- Internationalization of string sorting with locale module
110 if type(item1
) == type('') or type(item2
) == type(''):
111 cmpVal
= locale
.strcoll(str(item1
), str(item2
))
113 cmpVal
= cmp(item1
, item2
)
116 # If the items are equal then pick something else to make the sort value unique
118 cmpVal
= apply(cmp, self
.GetSecondarySortValues(col
, key1
, key2
))
126 def __updateImages(self
, oldCol
):
127 sortImages
= self
.GetSortImages()
128 if self
._col
!= -1 and sortImages
[0] != -1:
129 img
= sortImages
[self
._colSortFlag
[self
._col
]]
130 list = self
.GetListCtrl()
132 list.ClearColumnImage(oldCol
)
133 list.SetColumnImage(self
._col
, img
)
136 #----------------------------------------------------------------------------
137 #----------------------------------------------------------------------------
139 class wxListCtrlAutoWidthMixin
:
140 """ A mix-in class that automatically resizes the last column to take up
141 the remaining width of the wxListCtrl.
143 This causes the wxListCtrl to automatically take up the full width of
144 the list, without either a horizontal scroll bar (unless absolutely
145 necessary) or empty space to the right of the last column.
147 NOTE: This only works for report-style lists.
149 WARNING: If you override the EVT_SIZE event in your wxListCtrl, make
150 sure you call event.Skip() to ensure that the mixin's
151 _OnResize method is called.
153 This mix-in class was written by Erik Westra <ewestra@wave.co.nz>
156 """ Standard initialiser.
158 self
._lastColMinWidth
= None
160 EVT_SIZE(self
, self
._onResize
)
161 EVT_LIST_COL_END_DRAG(self
, self
.GetId(), self
._onResize
)
164 def resizeLastColumn(self
, minWidth
):
165 """ Resize the last column appropriately.
167 If the list's columns are too wide to fit within the window, we use
168 a horizontal scrollbar. Otherwise, we expand the right-most column
169 to take up the remaining free space in the list.
171 This method is called automatically when the wxListCtrl is resized;
172 you can also call it yourself whenever you want the last column to
173 be resized appropriately (eg, when adding, removing or resizing
176 'minWidth' is the preferred minimum width for the last column.
178 self
._lastColMinWidth
= minWidth
181 # =====================
182 # == Private Methods ==
183 # =====================
185 def _onResize(self
, event
):
186 """ Respond to the wxListCtrl being resized.
188 We automatically resize the last column in the list.
190 wxCallAfter(self
._doResize
)
195 """ Resize the last column as appropriate.
197 If the list's columns are too wide to fit within the window, we use
198 a horizontal scrollbar. Otherwise, we expand the right-most column
199 to take up the remaining free space in the list.
201 We remember the current size of the last column, before resizing,
202 as the preferred minimum width if we haven't previously been given
203 or calculated a minimum width. This ensure that repeated calls to
204 _doResize() don't cause the last column to size itself too large.
206 numCols
= self
.GetColumnCount()
207 if numCols
== 0: return # Nothing to resize.
209 if self
._lastColMinWidth
== None:
210 self
._lastColMinWidth
= self
.GetColumnWidth(numCols
- 1)
212 # We're showing the vertical scrollbar -> allow for scrollbar width
213 # NOTE: on GTK, the scrollbar is included in the client size, but on
214 # Windows it is not included
215 listWidth
= self
.GetClientSize().width
216 if wxPlatform
!= '__WXMSW__':
217 if self
.GetItemCount() > self
.GetCountPerPage():
218 scrollWidth
= wxSystemSettings_GetSystemMetric(wxSYS_VSCROLL_X
)
219 listWidth
= listWidth
- scrollWidth
221 totColWidth
= 0 # Width of all columns except last one.
222 for col
in range(numCols
-1):
223 totColWidth
= totColWidth
+ self
.GetColumnWidth(col
)
225 lastColWidth
= self
.GetColumnWidth(numCols
- 1)
227 if totColWidth
+ self
._lastColMinWidth
> listWidth
:
228 # We haven't got the width to show the last column at its minimum
229 # width -> set it to its minimum width and allow the horizontal
231 self
.SetColumnWidth(numCols
-1, self
._lastColMinWidth
)
234 # Resize the last column to take up the remaining available space.
236 self
.SetColumnWidth(numCols
-1, listWidth
- totColWidth
)
240 #----------------------------------------------------------------------------
242 SEL_FOC
= wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED
243 def selectBeforePopup(event
):
244 """Ensures the item the mouse is pointing at is selected before a popup.
246 Works with both single-select and multi-select lists."""
247 ctrl
= event
.GetEventObject()
248 if isinstance(ctrl
, wxListCtrl
):
249 n
, flags
= ctrl
.HitTest(event
.GetPosition())
251 if not ctrl
.GetItemState(n
, wxLIST_STATE_SELECTED
):
252 for i
in range(ctrl
.GetItemCount()):
253 ctrl
.SetItemState(i
, 0, SEL_FOC
)
254 #for i in getListCtrlSelection(ctrl, SEL_FOC):
255 # ctrl.SetItemState(i, 0, SEL_FOC)
256 ctrl
.SetItemState(n
, SEL_FOC
, SEL_FOC
)
258 def getListCtrlSelection(listctrl
, state
=wxLIST_STATE_SELECTED
):
259 """ Returns list of item indexes of given state (selected by defaults) """
263 idx
= listctrl
.GetNextItem(idx
, wxLIST_NEXT_ALL
, state
)
269 class ListCtrlSelectionManagerMix
:
270 """Mixin that defines a platform independent selection policy
272 As selection single and multi-select list return the item index or a
273 list of item indexes respectively.
275 wxEVT_DOPOPUPMENU
= wxNewId()
279 EVT_RIGHT_DOWN(self
, self
.OnLCSMRightDown
)
280 self
.Connect(-1, -1, self
.wxEVT_DOPOPUPMENU
, self
.OnLCSMDoPopup
)
282 def getPopupMenu(self
):
283 """ Override to implement dynamic menus (create) """
286 def setPopupMenu(self
, menu
):
287 """ Must be set for default behaviour """
290 def afterPopupMenu(self
, menu
):
291 """ Override to implement dynamic menus (destroy) """
294 def getSelection(self
):
295 res
= getListCtrlSelection(self
)
296 if self
.GetWindowStyleFlag() & wxLC_SINGLE_SEL
:
304 def OnLCSMRightDown(self
, event
):
305 selectBeforePopup(event
)
307 menu
= self
.getPopupMenu()
310 evt
.SetEventType(self
.wxEVT_DOPOPUPMENU
)
312 evt
.pos
= event
.GetPosition()
313 wxPostEvent(self
, evt
)
315 def OnLCSMDoPopup(self
, event
):
316 self
.PopupMenu(event
.menu
, event
.pos
)
317 self
.afterPopupMenu(event
.menu
)
319 #----------------------------------------------------------------------