so I know there are quite a lot of similar questions on here but none really gets to the specific point I am interested in.
I want to implement custom selection behavior of a QGraphicsItem
s (e.g. change its color on selection). Apparently this is handled by the items themselves so one needs to make an own class extending QGraphicsItem
. There, I am really missing something, like an onSelectionToggled
method (slot) that one could override. But I finally figured out that one has to override the mousePressEvent
method (after all "selection" is just a more concrete term for the abstract concept of a left-click).
So if in this method I call:
setPen( QPen( QColor( "orange" ) ) );
update();
The color actually changes when I click a single item.
But not when the selection happens via the rubber band of the scene.
Since there is no onSelectionToggled
, I imagined the scene would "simulate" a respective mouse event for the intersected items.
Since this is not the case, my question is: "How can I react to such a selection via rubber band?" Ideally in a "unified" way (no extra code for individual selection by mouse click).
Also, I wonder how I can prevent the dotted bounding rectangle to be drawn on selection. I don't want it and was hoping to get rid of it automatically when subclassing QGraphicsItem
.
The QGraphicsItem
class is the base class for all graphical items in a QGraphicsScene
. It is the QGraphicsScene
class that contains all the functionality for handling QGraphicsItem
selection. If you catch the signal QGraphicsScene::selectionChanged()
you should be able to find the selected items through
`QList<QGraphicsItem *> QGraphicsScene::selectedItems()`
you can then change the pen for those items and redraw.
Of course since you want the items to turn back to their original colour once they are unselected, perhaps a better approach is to iterate over all items (QList<QGraphicsItem *> QGraphicsScene::items()
) and check their isSelected()
state to change their pen into the appropriate colour.