PDA

View Full Version : Attaching Actions to Items in a QGraphicsScene



Goug
13th October 2011, 04:51
I have an application using a QGraphicsScene where some items within the scene have actions associated with them and some don't. If an action is associated, the user can click on that item to trigger the action (calling up a different set of objects, triggering a function, popping up a menu, etc.). I'm setting the ItemIsSelectable flag on the actionable items, and I have a slot attached to the scene's "selectionChanged" signal. All of this work's as expected.

However, I run into strange behavior when I programmatically de-select the selected item. I can't leave it selected because the user might click on the same object again; if it's already selected, it doesn't get re-selected, the list of selected items in the scene doesn't change, and the signal doesn't fire.
So, after processing the action associated with the selected item, I call the item's "setSelected" method to clear it's selection. At that time, I expect the "selectionChanged" signal to fire, and the list of selected items is empty. That all happens.

The weird issue is that it all happens again, effectively triggering the action twice. Here's what I see:

1. No items are currently selected.
2. The user single-clicks on a selectable item.
3. The scene's selectionChanged signal fires, and there is one selected item in the selected item's list.
4. Process the action associated with the item.
5. Call the item's setSelected method to deselect it.
6. The scene's selectionChanged signal fires, and the list of selected items is empty. (All normal to here.)
7. The scene's selectionChanged signal fires with the originally selected item re-selected.
8. The action is processed again (since it looks as if the user selected the item again).
9. The item is programmatically de-selected again.
10. The scene's selectionChanged signal fires, and the list of selected items is empty.
11. End

It's almost as if, when the item is originally selected, the scene sets the selected flag twice, and in between, my slot is processing the action.

I've tried using a queued connection for the signal/slot connection instead if the default, and that didn't change anything. I don't know if there's a better way to perform these actions, and if so, recommendations would be welcome.

The only solution I've been able to come up with is kludy and I don't like it, but that's to remember the address of the previously selected item, and if a selection comes in twice in a row, ignore the second one.

Thoughts?

Doug

wysota
13th October 2011, 10:26
Don't use the selected flag. Instead reimplement mousePressEvent() or mouseReleaseEvent() for your items and trigger your action from within there. You can also reimplement mouse events for the scene and not the items to handle the situation there.