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);

    I tried this
    foreach (Spirit c, spitem)



    foreach (QPointer <Spirit> c, spitem)



    but i get @QPointer is not a class@

  • You need to include the correct header for QPointer.

    QGraphicsScene::items() then will give you the QList<QGraphicsItem*>, which you should use in foreach.

  • 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.

  • Yes that is possible too, only it is on instance level instead of class level. It saves on creating your own hierarchy thou. I am not sure if it will end up using more memory than just having a method that returns a hard-coded enum value.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.