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 varia开发者_StackOverflow社区ble and expect it to still be visible in the group, which is declared outside of this for loop?
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.
If you declare your QGraphicsPixmapItem as a stack variable, it will be destructed at each iteration of the loop. Therefore, using its address as a pointer for the QGraphicsItemGroup::addToGroup method will most likely lead to a segmentation fault later in the program.
精彩评论