问题
I enconutered a problem, when dealing with QGraphicsScene and QPixmap. I am sequentially displaying frames, captured by the camera. QTimer object is calling updateSingleView() function every 100ms. That is my inner function:
void CCIGui::updateSingleView()
{
unsigned char *const img = PGRSystem->SnapShot();
QImage Img(img, 1024, 768, QImage::Format_RGB888);
scenes.at(0)->removeItem(scenes.at(0)->items().at(0));
scenes.at(0)->addPixmap(QPixmap::fromImage(Img));
ui_camViews.at(0).graphicsView->setScene(scenes.at(0));
delete [] img;
}
Gui is displaying the camera's view but unfortunatelly there is a memory leak, when calling scenes.at(0)->addPixmap(QPixmap::fromImage(Img));
I thought that removeItem
function should destroy the old QPixmap, but apparently its not. Do you know why the leak occurs and how to solve it?
回答1:
As suggested
you need to delete the item after removeItem line.
i.e
QPointer _item = scenes.at(0)->items().at(0); scenes.at(0)->removeItem( _item ); delete _item;
scenes.at(0)->addPixmap(QPixmap::fromImage(Img));
.....
回答2:
From the Qt documentation:
void QGraphicsScene::removeItem ( QGraphicsItem * item )
Removes the item item and all its children from the scene. The ownership of item is passed on to the caller (i.e., QGraphicsScene will no longer delete item when destroyed).
See also addItem().
Hence you need to delete the item using delete
manually.
http://doc.trolltech.com/4.7/qgraphicsscene.html#removeItem
来源:https://stackoverflow.com/questions/4265046/removing-qpixmap-from-qgraphicsscene