Search code examples
qtqgraphicsviewqgraphicsitemqgraphicsscene

Display a QGraphicsItem several times


I need to manage a scene with a high number of static item, but some item will be the same but at 10k+ different coordinates. For example, there's one circle, but drawed 10k times in the scene.

The only solution I found was to use 2 scenes for the same viewport, which is obviously not the solution I need since I need many simple objects. It it possible to do this using QGraphicsScene/QgraphicView ?


Solution

  • is it possible to instanciate one object then place it 40000 times

    No, Qt doesn't work like this. That's like asking if you can be in two places at the same time.

    Qt is designed to be efficient, so that if you have multiple objects, for example a QGraphicsPixmapItem with the same resource image, it can use the same image for all the items. However, an item can only be at one location in the scene at any one time.

    So, in the case of a circle, drawn 10000 times, you can create 10000 graphics items, all using the same QPixmap resource, which is the circle. However, you still need to create 10000 items as each item must store its coordinates and orientation somewhere; that being the QGraphicsItem.

    Let's say we have instantiated a QPixmap item with the circle:

    QPixmap* pCircle = new QPixmap(":/images/circle"); // circle from the resource system
    

    We can now create 10000 items, at different locations, each using that circle:

    for(int i = 0; i<10000; ++i)
    {
        QGraphicsPixmapItem* pItem = new QGraphicsPixmapItem(*pCircle);
        // set its position and add it to the scene
        pItem->setPos(x, y);
        m_pScene->addItem(pItem);
    }