View Full Version : Querying object type using itemAt

24th June 2009, 17:25
I'm writing an application that uses QGraphicsScene and subclassed QGraphicsItems, based on the Diagram Scene demo app. The user can click on the scene and select an item, which can be either a DiagramItem (which inherits QGraphicsPolygonItem), or an Arrow (which inherits QGraphicsLineItem).

I need to distinguish the class that the selected object belongs to, but I'm not sure how to do it. Below is the relevant code from my subclassed QGraphicsScene class (DiagramScene):

void DiagramScene::mousePressEvent(QGraphicsSceneMouseE vent *event)
if (itemAt(event->scenePos())) {

DiagramItem *selectedItem = qgraphicsitem_cast<DiagramItem *>(itemAt(event->scenePos()));
// operate on selectedItem

How can I modify this to check whether I've selected a DiagramItem or an Arrow, and then process selectedItem accordingly? At the moment the app crashes when I click on an Arrow object. (I thought about using exception handling, but am not sure how you try and catch casting errors.)

Any advice would be greatly appreciated!

24th June 2009, 17:35
Ah, figured out a solution - qgraphicsitem_cast returns a zero if the cast doesn't work, so can try and recast it using the other class type if that's the case.