3

i have a little problem

I am programming Petri Net simulator...

I have two different classes

    class PNItem : public QObject, public QGraphicsItem
    ...

and

    class PNEdge : public QGraphicsLineItem

when i call...

    QGraphicsItem *QGraphicsScene::ItemAt(//cursor position)

, is it possible somehow to get to know, what item i have clicked on? resp. what item is given item by ItemAt?

Marty
  • 95
  • 2
  • 9

2 Answers2

4

Since you've only got two types, you could just use dynamic_casting, and check to see if the cast was successful:

QGraphicsItem *item = scene->ItemAt(pos);
PNEdge *as_pnedge;
PNItem *as_pnitem;
if((as_pnedge = dynamic_cast<PNEdge*>(item))){
    // do stuff with as_pnedge
}else if((as_pnitem = dynamic_cast<PNItem*>(item))){
    // do stuff with as_pnitem
}
James
  • 24,676
  • 13
  • 84
  • 130
4

GraphicsItem::type() is intended to be used to solve this problem.

So you would do something like this for example:

enum ItemType { TypePNItem = QGraphicsItem::UserType + 1,
                TypePNEdge = QGraphicsItem::UserType + 2 }

class PNItem : public QObject, public QGraphicsItem {

    public:
        int type() { return TypePNItem; }
    ...

};

Which would then allow you to do this:

QGraphicsItem *item = scene->itemAt( x, y );
switch( item->type() )
{
    case PNItem:
         ...
         break;
}

doing this also enables the usage of qgraphicsitem_cast

See also: QGraphicsItem::UserType

Chris
  • 17,119
  • 5
  • 57
  • 60