Best way to handle ...



  • Hi Qt Community,

    I'm just looking for the best way to handle this situation , which I'm sure that many Qt programmers have encountered (but have easily found a solution for it :b)

    In short terms , I have this class A :

    Class A : public QGraphicsItem
    {
    // Constructors , destructor etc...
    void doSmth ();
    // Some attributes...
    }
    

    And , I have a

    class B : public QGraphicsItem{//stuff}
    

    So in my subclassed QGraphicsScene , I want to catch the collidingItems of class B , but since it returns a list of QGraphicsItem :

    SubScene::method ()
    {
    //bItem is one of the attributes of my subScene
    QList<QGraphicsItem*> colItems = bItem->collidingItems ();
    for (int i=0;i <colItems.size ();i++)
    {
    If (dynamic_cast <A*>(colItems.at (i)))
          colItems.at (i)->doSmth (); //obviously impossible 
    }
    }
    

    I have tried to use ready Lists of class A , but i dont believe them to be the best and safest solution to this.

    Any ideas ? I'll be grateful ;)


  • Lifetime Qt Champion

    Hi,

    It should rather be:

    A * aItem = dynamic_cast(colItems.at(i));
    if (aItem) {
        aItem->doSmth();
    }
    


  • Awesome , I never knew it can work this way , however ... doesn't this trick use slightly more memory , or it only helps to build up the reference ?


  • Lifetime Qt Champion

    It's not a trick, that's how you use dynamic_cast.

    You don't create a new object. You will use a local variable that is a pointer to your object or null if colItems.at(i) is not a pointer to an A object. Local variable that will be destroyed at the end of the function.


Log in to reply
 

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