Search code examples
c++qtqt4qgraphicsview

Heap/Stack - Scope of variables going into QGraphicsItemGroup


If I have a QGraphicsItem that I want to put in a QGraphicsItemGroup, in a loop..like so:

for(int i =0; i < 2; i++)
{
    for(int j = 0; j < 2; j++)
    {
        QPixmap p(imwidth, imheight);
        p.fill(Qt::gray);
        QGraphicsPixmapItem *ipi = new QGraphicsPixmapItem(p);
        group->addToGroup(ipi);
    }
}

is it necessary for that item to be on the heap, or can I make it a stack variable and expect it to still be visible in the group, which is declared outside of this for loop?


Solution

  • The addToGroup method takes a pointer, so you can't get away with passing it anything else. It doesn't copy the objects passed in, just stores that pointer.

    If you give it a pointer to stack-allocated objects, it will blow up sooner or later trying to access stack memory which will (probably) have been overwritten since then, and even if it (miraculously) hasn't been overwritten, those objects will have been destroyed anyway - so they'll be invalid in any case.