QGraphicsScene :: itemAt () - how to recognize custom classes

I have a little problem

I am programming a 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 to somehow find out which element I clicked on? accordingly, what item is set by ItemAt?

+3
source share
2 answers

GraphicsItem :: type () is designed 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; }
    ...

};

What will allow you to do this:

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

it also allows you to use qgraphicsitem_cast

See also: QGraphicsItem :: UserType

+4
source

, dynamic_cast ing , :

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
}
+4

All Articles