qtqgraphicssceneqgraphicsitem

Filter QGraphicsItems type in a scene from items()


I'm looking for a way to get all the QGraphicsLineItem from a scene, using items().

It gives a list of all the QGraphicsItem, but I want to perform actions only on QGraphicsLine for example. How can I sort this list/extract the items I want with a specific type ?


Solution

  • You can go through the list and test the type with a dynamic_cast:

    // I'm not sure where you want to implement this,
    // but it can be in your derived GraphicsScene class.
    // Else, just call scene->items() and make a new list
    // outside of the scene class.
    void CustomScene::foo()
    {
        QList<QGraphicsItem*> itemList = items();
        for (int i = 0; i < itemList.size(); ++i) {
             if (auto lineItem{dynamic_cast<QGraphicsLineItem*>(itemList[i])})
                 // do a specific action or put this in a QList of QGraphicsLiteItem*s
                 // and return that list instead of void
                 ;
        }
    }
    

    I haven't tested this code, but something like this should be possible.