Introduction
This recipe offers a wxListBox subclass that will jump directly to the item that starts with the phrase you type in (as opposed to selecting the next item that starts with the character you just typed). It is similar to the functionality provided by Mozilla's select boxes, while the default behavior is similiar to Internet Explorer's.
What Objects are Involved
Only wxListBox itself.
Process Overview
When the user presses any key except backspace, that key is appended to a phrase (backspace erases the last character). The wxListBox then deselects any items already selected and goes to the first item that begins with the phrase typed. The process is case insensitive.
Special Concerns
If you plan to use any method other than Set to add items to the wxListBox (such as Append), you need to provide a method for it that sets self.choices to the items that make up the wxListBox.
Code Sample
1 import wx
2
3 class PromptingListBox(wx.ListBox):
4 def __init__(self, parent, id, choices = [], style = 0):
5 self.choices = choices
6 self.phrase = ''
7 wx.ListBox.__init__(self, parent, id, choices = choices, style = style)
8 self.Bind(wx.EVT_CHAR, self.EvtChar, self)
9 return 0
10
11 def EvtChar(self, event):
12 keycode = event.GetKeyCode()
13 if keycode == 8:
14 # Backspace removes last letter
15 self.phrase = self.phrase[:-1]
16 elif keycode == 127:
17 # Delete erases phrase
18 self.phrase = ''
19 elif keycode not in range(256):
20 # Do the default action for nonascii keycodes
21 event.Skip()
22 return 0
23 else:
24 self.phrase += chr(keycode).lower()
25 for item in self.GetSelections():
26 self.Deselect(item)
27 if self.phrase == '':
28 # Don't select 1st item if phrase is blank
29 return 0
30 for choice in self.choices:
31 choice = choice.lower()
32 if choice.startswith(self.phrase):
33 self.SetStringSelection(choice)
34 return 0
35 return 0
36
37 def Set(self, choices):
38 self.choices = choices
39 self.phrase = ''
40 wx.ListBox.Set(self, choices)
41 return 0
Comments
Send questions or comments to Jeremy Evans. Bill Bell's Combo Box that Suggests Options gave me the general idea about how to do this, this code is based on it.