Search code examples
wxpythonwxwidgets

Keeping at least one item selected in a wxListBox


I have a multiple selection wxListBox and I want to keep the condition that at least one of the items in the list is selected. I tried having

def OnSelectDataSource(self, event):
    datasourcelist = xrc.XRCCTRL(self, "m_lstDataSource")
    if not event.IsSelection():
        if len(datasourcelist.GetSelections()) == 0:
            datasourcelist.Select(event.GetInt())

as the handler for the wx.EVT_LISTBOX event. This works, but you can see the item be deselected and then reselected. There's probably a better method that I don't know of.

The deselection seems to be happening on mouse press down, and the event doesn't get called until mouse press up (and then the item is reselected).


Based on the suggested solution, I now have it working, with

xrc.XRCCTRL(self, "m_lstDataSource").Bind(wx.EVT_LEFT_DOWN, self.CheckDataSelect)

in my __init__ method and

def CheckDataSelect(self, event):
    lstctrl = xrc.XRCCTRL(self, "m_lstDataSource")
    pos = lstctrl.HitTest(event.GetPosition())
    if lstctrl.GetSelections() == (pos,):
        event.Skip(False)
    else:
        event.Skip()

Solution

  • Capture the mouse up event and do your check to see if this will make the selection go to no items. If so, call event.skip() to prevent further handlers from touching your selection.

    http://www.wxpython.org/docs/api/wx.Event-class.html#Skip