Beginners: how to loop qphraphicsobjects in a scene
-
Hi Guys,
I have custom objects in a game, with inheritance from QGraphicsObject = QGraphicsItems + QObject
Now in the game, I want to make a foreach . can some body help me?
I defined the objects this and then I added them to the scene
@
QPointer <Spirit> spitem = new Spirit(this);
scene->addItem(spitem);
@I tried this
@
foreach (Spirit c, spitem)
{}
and
foreach (QPointer <Spirit> c, spitem)
{
}@
but i get @QPointer is not a class@
-
Hello my friend
I understood it this way
@
QList<QGraphicsItem *> spirits = scene->items();
foreach (QGraphicsItem *item, spirits) {
}
@But how can select certain spirits using their class names?
-
You can type check during runtime with qobject_cast or dynamic_cast and proceed accordingly. If the existing object matches the cast parameter you will get a valid pointer, if not the pointer will be null.
If you have multiple QGraphicsItem derived classes and you need to proceed according to type for every one of them using a cascade of casts is probably a bad idea, in this case you need to create your own QGraphicsItem derived hierarchy with a virtual method to return like an enum of all the types, statically cast the scene->items() pointer to your base type and use a switch statement to switch to the correct case instead of going through them all with the dynamic cast.
-
Thank you guys.
I made it using @item->setdata@ and @item->data@ While creating the item i set its data and in the game, I read its data.