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 *
15 #----------------------------------------------------------------------------
17 class wxColumnSorterMixin
:
19 A mixin class that handles sorting of a wxListCtrl in REPORT mode when
20 the column header is clicked on.
22 There are a few requirments needed in order for this to work genericly:
24 1. The combined class must have a GetListCtrl method that
25 returns the wxListCtrl to be sorted, and the list control
26 must exist at the time the wxColumnSorterMixin.__init__
27 method is called because it uses GetListCtrl.
29 2. Items in the list control must have a unique data value set
30 with list.SetItemData.
32 3. The combined class must have an attribute named itemDataMap
33 that is a dictionary mapping the data values to a sequence of
34 objects representing the values in each column. These values
35 are compared in the column sorter to determine sort order.
37 Interesting methods to override are GetColumnSorter,
38 GetSecondarySortValues, and GetSortImages. See below for details.
41 def __init__(self
, numColumns
):
42 self
._colSortFlag
= [0] * numColumns
45 list = self
.GetListCtrl()
47 raise ValueError, "No wxListCtrl available"
48 EVT_LIST_COL_CLICK(list, list.GetId(), self
.__OnColClick
)
51 def SortListItems(self
, col
=-1, ascending
=1):
52 """Sort the list on demand. Can also be used to set the sort column and order."""
56 self
._colSortFlag
[col
] = ascending
57 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
58 self
.__updateImages
(oldCol
)
61 def GetColumnWidths(self
):
63 Returns a list of column widths. Can be used to help restore the current
66 list = self
.GetListCtrl()
68 for x
in range(len(self
._colSortFlag
)):
69 rv
.append(list.GetColumnWidth(x
))
73 def GetSortImages(self
):
75 Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column
76 header when sorting in descending order.
78 return (-1, -1) # (decending, ascending) image IDs
81 def GetColumnSorter(self
):
82 """Returns a callable object to be used for comparing column values when sorting."""
83 return self
.__ColumnSorter
86 def GetSecondarySortValues(self
, col
, key1
, key2
):
87 """Returns a tuple of 2 values to use for secondary sort values when the
88 items in the selected column match equal. The default just returns the
93 def __OnColClick(self
, evt
):
95 self
._col
= col
= evt
.GetColumn()
96 self
._colSortFlag
[col
] = not self
._colSortFlag
[col
]
97 self
.GetListCtrl().SortItems(self
.GetColumnSorter())
98 self
.__updateImages
(oldCol
)
102 def __ColumnSorter(self
, key1
, key2
):
104 ascending
= self
._colSortFlag
[col
]
105 item1
= self
.itemDataMap
[key1
][col
]
106 item2
= self
.itemDataMap
[key2
][col
]
108 cmpVal
= cmp(item1
, item2
)
110 # If the items are equal then pick something else to make the sort value unique
112 cmpVal
= apply(cmp, self
.GetSecondarySortValues(col
, key1
, key2
))
120 def __updateImages(self
, oldCol
):
121 sortImages
= self
.GetSortImages()
122 if self
._col
!= -1 and sortImages
[0] != -1:
123 img
= sortImages
[self
._colSortFlag
[self
._col
]]
124 list = self
.GetListCtrl()
126 list.ClearColumnImage(oldCol
)
127 list.SetColumnImage(self
._col
, img
)
130 #----------------------------------------------------------------------------
131 #----------------------------------------------------------------------------
133 class wxListCtrlAutoWidthMixin
:
134 """ A mix-in class that automatically resizes the last column to take up
135 the remaining width of the wxListCtrl.
137 This causes the wxListCtrl to automatically take up the full width of
138 the list, without either a horizontal scroll bar (unless absolutely
139 necessary) or empty space to the right of the last column.
141 NOTE: This only works for report-style lists.
143 WARNING: If you override the EVT_SIZE event in your wxListCtrl, make
144 sure you call event.Skip() to ensure that the mixin's
145 _OnResize method is called.
147 This mix-in class was written by Erik Westra <ewestra@wave.co.nz>
150 """ Standard initialiser.
152 self
._needResize
= false
153 self
._lastColMinWidth
= None
155 EVT_SIZE(self
, self
._onResize
)
156 EVT_LIST_COL_END_DRAG(self
, self
.GetId(), self
._onEndColDrag
)
157 EVT_IDLE(self
, self
._onIdle
)
160 def resizeLastColumn(self
, minWidth
):
161 """ Resize the last column appropriately.
163 If the list's columns are too wide to fit within the window, we use
164 a horizontal scrollbar. Otherwise, we expand the right-most column
165 to take up the remaining free space in the list.
167 This method is called automatically when the wxListCtrl is resized;
168 you can also call it yourself whenever you want the last column to
169 be resized appropriately (eg, when adding, removing or resizing
172 'minWidth' is the preferred minimum width for the last column.
174 self
._lastColMinWidth
= minWidth
177 # =====================
178 # == Private Methods ==
179 # =====================
181 def _onResize(self
, event
):
182 """ Respond to the wxListCtrl being resized.
184 We automatically resize the last column in the list.
189 def _onEndColDrag(self
, event
):
190 """ Respond to the user resizing one of our columns.
192 We resize the last column in the list to match. Note that, because
193 of a quirk in the way columns are resized under MS Windows, we
194 actually have to do the column resize in idle time.
196 self
._needResize
= true
200 def _onIdle(self
, event
):
201 """ Respond to an idle event.
203 We resize the last column, if we've been asked to do so.
207 self
.Refresh() # Fixes redraw problem under MS Windows.
208 self
._needResize
= false
213 """ Resize the last column as appropriate.
215 If the list's columns are too wide to fit within the window, we use
216 a horizontal scrollbar. Otherwise, we expand the right-most column
217 to take up the remaining free space in the list.
219 We remember the current size of the last column, before resizing,
220 as the preferred minimum width if we haven't previously been given
221 or calculated a minimum width. This ensure that repeated calls to
222 _doResize() don't cause the last column to size itself too large.
224 numCols
= self
.GetColumnCount()
225 if numCols
== 0: return # Nothing to resize.
227 if self
._lastColMinWidth
== None:
228 self
._lastColMinWidth
= self
.GetColumnWidth(numCols
- 1)
230 listWidth
= self
.GetSize().width
231 if self
.GetItemCount() > self
.GetCountPerPage():
232 # We're showing the vertical scrollbar -> allow for scrollbar width
233 scrollWidth
= wxSystemSettings_GetSystemMetric(wxSYS_VSCROLL_X
)
234 listWidth
= listWidth
- scrollWidth
236 totColWidth
= 0 # Width of all columns except last one.
237 for col
in range(numCols
-1):
238 totColWidth
= totColWidth
+ self
.GetColumnWidth(col
)
240 lastColWidth
= self
.GetColumnWidth(numCols
- 1)
242 # NOTE: This is the extra number of pixels required to make the
243 # wxListCtrl size correctly, at least under Windows 2000.
244 # Unfortunately, different OSs and even different versions of the
245 # same OS may implement the wxListCtrl differently, so different
246 # margins may be needed to get the columns resized correctly. No
247 # doubt the margin could be calculated in a more intelligent
249 if wxPlatform
== '__WXMSW__':
251 elif wxPlatform
== '__WXGTK__':
256 if totColWidth
+ self
._lastColMinWidth
> listWidth
- margin
:
257 # We haven't got the width to show the last column at its minimum
258 # width -> set it to its minimum width and allow the horizontal
260 self
.SetColumnWidth(numCols
-1, self
._lastColMinWidth
)
263 # Resize the last column to take up the remaining available space.
265 self
.SetColumnWidth(numCols
-1, listWidth
- totColWidth
- margin
)
269 #----------------------------------------------------------------------------
271 SEL_FOC
= wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED
272 def selectBeforePopup(event
):
273 """Ensures the item the mouse is pointing at is selected before a popup.
275 Works with both single-select and multi-select lists."""
276 ctrl
= event
.GetEventObject()
277 if isinstance(ctrl
, wxListCtrl
):
278 n
, flags
= ctrl
.HitTest(event
.GetPosition())
280 if not ctrl
.GetItemState(n
, wxLIST_STATE_SELECTED
):
281 for i
in range(ctrl
.GetItemCount()):
282 ctrl
.SetItemState(i
, 0, SEL_FOC
)
283 #for i in getListCtrlSelection(ctrl, SEL_FOC):
284 # ctrl.SetItemState(i, 0, SEL_FOC)
285 ctrl
.SetItemState(n
, SEL_FOC
, SEL_FOC
)
287 def getListCtrlSelection(listctrl
, state
=wxLIST_STATE_SELECTED
):
288 """ Returns list of item indexes of given state (selected by defaults) """
292 idx
= listctrl
.GetNextItem(idx
, wxLIST_NEXT_ALL
, state
)
298 class ListCtrlSelectionManagerMix
:
299 """Mixin that defines a platform independent selection policy
301 As selection single and multi-select list return the item index or a
302 list of item indexes respectively.
304 wxEVT_DOPOPUPMENU
= wxNewId()
308 EVT_RIGHT_DOWN(self
, self
.OnLCSMRightDown
)
309 self
.Connect(-1, -1, self
.wxEVT_DOPOPUPMENU
, self
.OnLCSMDoPopup
)
311 def getPopupMenu(self
):
312 """ Override to implement dynamic menus (create) """
315 def setPopupMenu(self
, menu
):
316 """ Must be set for default behaviour """
319 def afterPopupMenu(self
, menu
):
320 """ Override to implement dynamic menus (destroy) """
323 def getSelection(self
):
324 res
= getListCtrlSelection(self
)
325 if self
.GetWindowStyleFlag() & wxLC_SINGLE_SEL
:
333 def OnLCSMRightDown(self
, event
):
334 selectBeforePopup(event
)
336 menu
= self
.getPopupMenu()
339 evt
.SetEventType(self
.wxEVT_DOPOPUPMENU
)
341 evt
.pos
= event
.GetPosition()
342 wxPostEvent(self
, evt
)
344 def OnLCSMDoPopup(self
, event
):
345 self
.PopupMenu(event
.menu
, event
.pos
)
346 self
.afterPopupMenu(event
.menu
)
348 #----------------------------------------------------------------------