Andrea Gavana wrote:
I think Cody is right: if you look at the wxPython demo for
wx.TreeCtrl and you change the style to wx.TR_MULTIPLE, moving up/down
with the arrows and holding the CTRL key down change the focus but
also the selections (you can see that the OnSelChanged event is called
every time).
Hm, interesting, in the demo with TR_MULTIPLE set, I see different behaviour
from what you describe. CTRL+UP/DOWN only changes the focus, not the selection,
for me in WinXP with wxPy 2.8.8.1, and so it should for consistency with the
rest of the OS. In the demo, on CTRL+UP/DOWN, the current set of selected (ie
highlighted with dark background) items remains unchanged, the focus box moves,
but unfortunately the return values from GetSelections() includes the currently
focused item, whether or not that item is actually selected (ie highlighted with
dark background).
This is probably related to bugs #626 and #2307 (6 and 3 years old respectively!):
http://trac.wxwidgets.org/ticket/626
http://trac.wxwidgets.org/ticket/2307
where a SEL_CHANGED event isn't fired when (de)selecting the currently focused
item in a tree with the wx.TR_MULTIPLE style. To work around this bug, I
disabled binding the SEL_CHANGED event, and manually called my OnSelChanged
handler on every mouse and keyboard event in the tree. Looking at the demo
though, I realized you can get the currently focused item by binding the
SEL_CHANGED event anyway and by grabbing its event.GetItem(). This is a hack,
since wx seems to treat a newly focused event as being selected, even if it's
only been focused. But it seems to work for now, so I'm happy.
So, to get the focused item, just call:
items = tree.GetSelections()
focusedItem = items[-1]
This doesn't always work, because the currently focused item isn't always the
last selected item, so you could never know for sure which of the items returned
by GetSelections() is the focused one.
For the fake key event, have you tried something like this:
keyEvent = wx.KeyEvent(wx.wxEVT_CHAR)
keyEvent.m_keyCode = wx.WXK_SPACE
wx.PostEvent(treeCtrl, keyEvent)
? It may need some tinkering, and I am not sure it will work, but you
never know...
Thanks for that. I thought for sure I'd tried tinkering with m_keyCode, but I
guess not. To this, I'd add:
keyEvent.m_controlDown = True
and now I've got myself what looks like a fake CTRL+SPACE that I can send to the
TreeCtrl. Great! Except posting the event to the treectrl doesn't actually
toggle the current selection for some reason. I guess it's not a good enough
fake after all. Just out of curiosity, what does the leading "m" in "m_" stand for?
Martin