Home > database >  How to get visible items bounding-box?
How to get visible items bounding-box?

Time:05-26

I have a scene that contains many QGraphicsItem items(about 25000 items) , When I hide useless items, How Can I get all visible items bounding-box, so that I can use fitInView ensure visible item just in the view center.

My Scene enter image description here

Wanted get visible items bounding-box
enter image description here

CodePudding user response:

I do not think there is any function for bounding getting rect of only visible items. I would use brute force, iterating over all visible items and calculating the total bounding rect. For example have a look at the implementation of QGraphicsScene::itemsBoundingRect() here https://code.woboq.org/qt5/qtbase/src/widgets/graphicsview/qgraphicsscene.cpp.html#_ZNK14QGraphicsScene17itemsBoundingRectEv and add visibility check to it.

QRectF visibleItemsBoundingRect() const
{
    QRectF boundingRect;
    const auto items_ = items();
    for (QGraphicsItem *item : items_)
    {
        if (item->isVisible()) // Note: this line was added to original implementation
            boundingRect |= item->sceneBoundingRect();
    }
    return boundingRect;
}

If this brute force performance is not satisfactory due to large number of invisible items, then you should probably keep some list of only visible items somewhere but you need to take the care to maintain it and update it everytime you show or hide or add or remove anything to the scene. Then you could iterate over such smaller list of items much faster. But I would not go this way unless the brute force method performance is really bad.

  • Related