Hello,
After filling a listbox with items, the user must be able to 1) search for a string, and 2) have the application highlight all the items in the listbox that contain that string.
I’m almost there, but listbox.SetSelection() expects an integer: How do I get the item’s index from its string?
class ListBoxFrame(wx.Frame):
def __init__(self, *args, **kwargs):
...
self.lb1 = wx.ListBox(panel, style=(wx.LB_MULTIPLE | wx.LB_ALWAYS_SB))
sizer.Add(self.lb1,1, wx.ALL | wx.EXPAND ,5)
...
def OnSearchButtonClick(self,event):
self.search_btn.Disable()
if (search := self.textbox.GetValue()):
for item in self.lb1.Items:
#found string in current list item
if search in item:
#HERE
self.lb1.SetSelection(int)
else:
self.statusbar.SetStatusText("Please type")
self.search_btn.Enable()
Cheers,
Edit: Found it. Still need to 1) ignore case and 2) find how to put the focus back to the top of the list after search+highlight
for i in range(self.lb1.GetCount()) :
item = self.lb1.GetString(i)
if search in item:
self.lb1.SetSelection(i)
#put focus back to top of the list
#BAD self.lb1.SetSelection(0)
–
Edit: Solved.
#one way to clear selections
dummy = [self.lb1.Deselect(i) for i in range(self.lb1.GetCount())]
...
hits = 0
for i in range(self.lb1.GetCount()) :
item = self.lb1.GetString(i)
#ignore case
if search.lower() in item.lower():
self.lb1.SetSelection(i)
hits += 1
self.statusbar.SetStatusText(f"Hits: {str(hits)}")
#put focus back to top of the list
self.lb1.SetFirstItem(0)