List Controls
Basic operation
- Associating python data with items
Selecting and manipulating items in wxListCtrls (using SetItem* methods) Report-view List controls "why don't my items show up" (missing headers) self.list.InsertColumn( 0, "Items", width=-1)
See Also:
Contents
-
List Controls
- Associating Python Data with Items
- Python Data Mixin
- Selecting Items Programmatically
- Retrieve Currently Selected Indices in List Control
- wxListCtrl's Hello world
- Changing fonts in a ListCtrl
- Unselecting an item programmatically
- Type Ahead Mixin
- Customizing ColumnSorterMixin to Sort Dates
- Drag and Drop with lists
- Drag and Drop with lists #2
- Drag and Drop with a striped drag list
Associating Python Data with Items
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 wxNew`Id) and keep a dict binding id to whatever data you want to associate.
So, for example:
1 id = wxNewId()
2 data_dict[ id ] = some_data_to_associate
3 listctrl.InsertStringItem( 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 wxListCtrl (Note that this appears to be a bug? Shouldn't need to use wxLIST_STATE_SELECTED for stateMask argument, should be able to use a MASK argument instead?):
self.SetItemState ( ID, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED )
It should be (I think):
self.SetItemState( ID, wxLIST_STATE_SELECTED, wxLIST_MASK_STATE )
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 = wxLIST_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
wxListCtrl's Hello world
It took half an hour for a newbie like me to get this tiny application running. Until I saw that you must call "InsertStringItem"
I was trying to use InsertItem.
1 import wx
2 class MyApp(wx.App):
3 def OnInit(self):
4 frame = wx.Frame(None, -1, "Hello from wxPython")
5
6 id=wx.NewId()
7 self.list=wx.ListCtrl(frame,id,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
8 self.list.Show(True)
9
10 self.list.InsertColumn(0,"Data #1")
11 self.list.InsertColumn(1,"Data #2")
12 self.list.InsertColumn(2,"Data #3")
13
14 # 0 will insert at the start of the list
15 pos = self.list.InsertStringItem(0,"hello")
16 # add values in the other columns on the same row
17 self.list.SetStringItem(pos,1,"world")
18 self.list.SetStringItem(pos,2,"!")
19
20 frame.Show(True)
21 self.SetTopWindow(frame)
22 return True
23
24 app = MyApp(0)
25 app.MainLoop()
Changing fonts in a ListCtrl
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:
1 import wx
2 # I'm using the new namespace. Hoorah!
3
4 # Note this is very much incomplete, and only dwells on how to set the font stuff in an attr.
5
6 class FancyListCtrl( wx.ListCtrl ):
7 def __init__( self, parent, id ):
8 wx.ListCtrl.__init__( self, parent, id, style = wx.LC_REPORT|wx.LC_VIRTUAL )
9 # We setup our pretty attribute once, here.
10 self._funky_attr = wx.ListItemAttr()
11 # This now contains default attributes.
12 # We can set the text colour to be different:
13 self._funky_attr.SetTextColour( wx.BLUE )
14 # But we can't do either of:
15 # self._funky_attr.GetFont().SetWeight( wx.BOLD )
16 # (Above fails silently - probably GetFont() returns a copy.)
17 # new_font = wx.Font()
18 # (No default constructor in wxPython.)
19 # But we can extract the default font:
20 new_font = self._funky_attr.GetFont()
21 # Set the weight on it:
22 new_font.SetWeight( wx.BOLD )
23 # Then put it back.
24 self._funky_attr.SetFont( new_font )
25 # self._funky_attr is now ready to be returned by OnGetItemAttr()
26 # (since this happens to be virtual.)
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
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, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED)
3
4 # unselecting
5 self.SetItemState(item, 0, wxLIST_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
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()
Drag and Drop with lists #2
1 """DnD demo with listctrl.
2 - Dragging of multiple selected items.
3 - Dropping on an empty list.
4 - Dropping of items on a list with a different number of columns.
5 - Dropping on a different applications."""
6
7 import cPickle
8 import wx
9
10 # ----------------------------------------------------------------------
11 # ----------------------------------------------------------------------
12 # DragList
13
14 class DragList(wx.ListCtrl):
15 def __init__(self, *arg, **kw):
16 wx.ListCtrl.__init__(self, *arg, **kw)
17
18 self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDrag)
19
20 dt = ListDrop(self)
21 self.SetDropTarget(dt)
22
23 def getItemInfo(self, idx):
24 """Collect all relevant data of a listitem, and put it in a list"""
25 l = []
26 l.append(idx) # We need the original index, so it is easier to eventualy delete it
27 l.append(self.GetItemData(idx)) # Itemdata
28 l.append(self.GetItemText(idx)) # Text first column
29 for i in range(1, self.GetColumnCount()): # Possible extra columns
30 l.append(self.GetItem(idx, i).GetText())
31 return l
32
33 def _startDrag(self, e):
34 """ Put together a data object for drag-and-drop _from_ this list. """
35 l = []
36 idx = -1
37 while True: # find all the selected items and put them in a list
38 idx = self.GetNextItem(idx, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
39 if idx == -1:
40 break
41 l.append(self.getItemInfo(idx))
42
43 # Pickle the items list.
44 itemdata = cPickle.dumps(l, 1)
45 # create our own data format and use it in a
46 # custom data object
47 ldata = wx.CustomDataObject("ListCtrlItems")
48 ldata.SetData(itemdata)
49 # Now make a data object for the item list.
50 data = wx.DataObjectComposite()
51 data.Add(ldata)
52
53 # Create drop source and begin drag-and-drop.
54 dropSource = wx.DropSource(self)
55 dropSource.SetData(data)
56 res = dropSource.DoDragDrop(flags=wx.Drag_DefaultMove)
57
58 # If move, we want to remove the item from this list.
59 if res == wx.DragMove:
60 # It's possible we are dragging/dropping from this list to this list. In which case, the
61 # index we are removing may have changed...
62
63 # Find correct position.
64 l.reverse() # Delete all the items, starting with the last item
65 for i in l:
66 pos = self.FindItem(i[0], i[2])
67 self.DeleteItem(pos)
68
69 def _insert(self, x, y, seq):
70 """ Insert text at given x, y coordinates --- used with drag-and-drop. """
71
72 # Find insertion point.
73 index, flags = self.HitTest((x, y))
74
75 if index == wx.NOT_FOUND: # not clicked on an item
76 if flags & (wx.LIST_HITTEST_NOWHERE|wx.LIST_HITTEST_ABOVE|wx.LIST_HITTEST_BELOW): # empty list or below last item
77 index = self.GetItemCount() # append to end of list
78 elif self.GetItemCount() > 0:
79 if y <= self.GetItemRect(0).y: # clicked just above first item
80 index = 0 # append to top of list
81 else:
82 index = self.GetItemCount() + 1 # append to end of list
83 else: # clicked on an item
84 # Get bounding rectangle for the item the user is dropping over.
85 rect = self.GetItemRect(index)
86
87 # If the user is dropping into the lower half of the rect, we want to insert _after_ this item.
88 # Correct for the fact that there may be a heading involved
89 if y > rect.y - self.GetItemRect(0).y + rect.height/2:
90 index += 1
91
92 for i in seq: # insert the item data
93 idx = self.InsertStringItem(index, i[2])
94 self.SetItemData(idx, i[1])
95 for j in range(1, self.GetColumnCount()):
96 try: # Target list can have more columns than source
97 self.SetStringItem(idx, j, i[2+j])
98 except:
99 pass # ignore the extra columns
100 index += 1
101
102 # ----------------------------------------------------------------------
103 # ----------------------------------------------------------------------
104 # ListDrop
105
106 class ListDrop(wx.PyDropTarget):
107 """ Drop target for simple lists. """
108
109 def __init__(self, source):
110 """ Arguments:
111 - source: source listctrl.
112 """
113 wx.PyDropTarget.__init__(self)
114
115 self.dv = source
116
117 # specify the type of data we will accept
118 self.data = wx.CustomDataObject("ListCtrlItems")
119 self.SetDataObject(self.data)
120
121 # Called when OnDrop returns True. We need to get the data and
122 # do something with it.
123 def OnData(self, x, y, d):
124 # copy the data from the drag source to our data object
125 if self.GetData():
126 # convert it back to a list and give it to the viewer
127 ldata = self.data.GetData()
128 l = cPickle.loads(ldata)
129 self.dv._insert(x, y, l)
130
131 # what is returned signals the source what to do
132 # with the original data (move, copy, etc.) In this
133 # case we just return the suggested value given to us.
134 return d
135
136 # ----------------------------------------------------------------------
137 # ----------------------------------------------------------------------
138 # main
139
140 if __name__ == '__main__':
141 items = ['Foo', 'Bar', 'Baz', 'Zif', 'Zaf', 'Zof']
142
143 class MyApp(wx.App):
144 def OnInit(self):
145 self.frame = wx.Frame(None, title='Main Frame')
146 self.frame.Show(True)
147 self.SetTopWindow(self.frame)
148 return True
149
150 app = MyApp(redirect=False)
151 dl1 = DragList(app.frame, style=wx.LC_LIST)
152 dl2 = DragList(app.frame, style=wx.LC_REPORT)
153 dl2.InsertColumn(0, "Column #0")
154 dl2.InsertColumn(1, "Column #1", wx.LIST_FORMAT_RIGHT)
155 dl2.InsertColumn(2, "Column #2")
156 sizer = wx.BoxSizer()
157 app.frame.SetSizer(sizer)
158 sizer.Add(dl1, proportion=1, flag=wx.EXPAND)
159 sizer.Add(dl2, proportion=1, flag=wx.EXPAND)
160
161 from random import choice
162 from sys import maxint
163
164 for item in items:
165 dl1.InsertStringItem(maxint, item)
166 idx = dl2.InsertStringItem(maxint, item)
167 dl2.SetStringItem(idx, 1, choice(items))
168 dl2.SetStringItem(idx, 2, choice(items))
169 app.frame.Layout()
170 app.MainLoop()
Drag and Drop with a striped drag list
This striped drag list allows for dragging and dropping within itself while maintaining its appearance. While not used in the example stub, it'll also stripe itself on an insert event (like from a pop-up file dialog) or on a delete event.
1 import wx
2
3 # dragliststriped.py
4
5 class DragListStriped(wx.ListCtrl):
6 def __init__(self, *arg, **kw):
7 wx.ListCtrl.__init__(self, *arg, **kw)
8
9 self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._onDrag)
10 self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._onSelect)
11 self.Bind(wx.EVT_LEFT_UP,self._onMouseUp)
12 self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
13 self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeaveWindow)
14 self.Bind(wx.EVT_ENTER_WINDOW, self._onEnterWindow)
15 self.Bind(wx.EVT_LIST_INSERT_ITEM, self._onInsert)
16 self.Bind(wx.EVT_LIST_DELETE_ITEM, self._onDelete)
17
18 #---------------
19 # Variables
20 #---------------
21 self.IsInControl=True
22 self.startIndex=-1
23 self.dropIndex=-1
24 self.IsDrag=False
25 self.dragIndex=-1
26
27 def _onLeaveWindow(self, event):
28 self.IsInControl=False
29 self.IsDrag=False
30 event.Skip()
31
32 def _onEnterWindow(self, event):
33 self.IsInControl=True
34 event.Skip()
35
36 def _onDrag(self, event):
37 self.IsDrag=True
38 self.dragIndex=event.m_itemIndex
39 event.Skip()
40 pass
41
42 def _onSelect(self, event):
43 self.startIndex=event.m_itemIndex
44 event.Skip()
45
46 def _onMouseUp(self, event):
47 # Purpose: to generate a dropIndex.
48 # Process: check self.IsInControl, check self.IsDrag, HitTest, compare HitTest value
49 # The mouse can end up in 5 different places:
50 # Outside the Control
51 # On itself
52 # Above its starting point and on another item
53 # Below its starting point and on another item
54 # Below its starting point and not on another item
55
56 if self.IsInControl==False: #1. Outside the control : Do Nothing
57 self.IsDrag=False
58 else: # In control but not a drag event : Do Nothing
59 if self.IsDrag==False:
60 pass
61 else: # In control and is a drag event : Determine Location
62 self.hitIndex=self.HitTest(event.GetPosition())
63 self.dropIndex=self.hitIndex[0]
64 # -- Drop index indicates where the drop location is; what index number
65 #---------
66 # Determine dropIndex and its validity
67 #--------
68 if self.dropIndex==self.startIndex or self.dropIndex==-1: #2. On itself or below control : Do Nothing
69 pass
70 else:
71 #----------
72 # Now that dropIndex has been established do 3 things
73 # 1. gather item data
74 # 2. delete item in list
75 # 3. insert item & it's data into the list at the new index
76 #----------
77 dropList=[] # Drop List is the list of field values from the list control
78 thisItem=self.GetItem(self.startIndex)
79 for x in range(self.GetColumnCount()):
80 dropList.append(self.GetItem(self.startIndex,x).GetText())
81 thisItem.SetId(self.dropIndex)
82 self.DeleteItem(self.startIndex)
83 self.InsertItem(thisItem)
84 for x in range(self.GetColumnCount()):
85 self.SetStringItem(self.dropIndex,x,dropList[x])
86 #------------
87 # I don't know exactly why, but the mouse event MUST
88 # call the stripe procedure if the control is to be successfully
89 # striped. Every time it was only in the _onInsert, it failed on
90 # dragging index 3 to the index 1 spot.
91 #-------------
92 # Furthermore, in the load button on the wxFrame that this lives in,
93 # I had to call the _onStripe directly because it would occasionally fail
94 # to stripe without it. You'll notice that this is present in the example stub.
95 # Someone with more knowledge than I probably knows why...and how to fix it properly.
96 #-------------
97 self._onStripe()
98 self.IsDrag=False
99 event.Skip()
100
101 def _onMouseDown(self, event):
102 self.IsInControl=True
103 event.Skip()
104
105 def _onInsert(self, event):
106 # Sequencing on a drop event is:
107 # wx.EVT_LIST_ITEM_SELECTED
108 # wx.EVT_LIST_BEGIN_DRAG
109 # wx.EVT_LEFT_UP
110 # wx.EVT_LIST_ITEM_SELECTED (at the new index)
111 # wx.EVT_LIST_INSERT_ITEM
112 #--------------------------------
113 # this call to onStripe catches any addition to the list; drag or not
114 self._onStripe()
115 self.dragIndex=-1
116 event.Skip()
117
118 def _onDelete(self, event):
119 self._onStripe()
120 event.Skip()
121
122 def _onStripe(self):
123 if self.GetItemCount()>0:
124 for x in range(self.GetItemCount()):
125 if x % 2==0:
126 self.SetItemBackgroundColour(x,wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT))
127 else:
128 self.SetItemBackgroundColour(x,wx.WHITE)
129
130 if __name__ == "__main__":
131 firstNameList = ["Ben", "Bruce", "Clark", "Dick"]
132 lastNameList = ["Grimm","Wayne", "Kent", "Grayson"]
133 superNameList = ["The Thing", "Batman", "Superman", "Robin"]
134
135 class ThisApp(wx.App):
136 def OnInit(self):
137 self.myFrame = wx.Frame(None, title='Drag List Striped Example')
138 self.myFrame.Show(True)
139 self.SetTopWindow(self.myFrame)
140 return True
141
142 myApp = ThisApp(redirect=False)
143 dls = DragListStriped(myApp.myFrame, style=wx.LC_REPORT|wx.LC_SINGLE_SEL)
144 dls.InsertColumn(0, "First Name")
145 dls.InsertColumn(1, "Last Name")
146 dls.InsertColumn(2, "Superhero Name")
147 sizer = wx.BoxSizer()
148 myApp.myFrame.SetSizer(sizer)
149 sizer.Add(dls, proportion=1, flag=wx.EXPAND)
150
151 for index in range(len(firstNameList)):
152 dls.InsertStringItem(index, firstNameList[index])
153 dls.SetStringItem(index, 1, lastNameList[index])
154 dls.SetStringItem(index, 2, superNameList[index])
155 myApp.myFrame.Layout()
156 dls._onStripe()
157 myApp.MainLoop()
The content on this page came from ListAndTreeControls, which was split up into this page and TreeControls .
