I had the same problem: I have a game application whose main window class inherits QMainWindow. Its constructor looks something like this:
m_scene = new QGraphicsScene; m_scene->setBackgroundBrush( Qt::black ); ... m_view = new QGraphicsView( m_scene ); ... setCentralWidget( m_view );
When I want to display the level of the game, I create an instance of QGridLayout into which I add QLabels and then set their pixmaps for specific images (pixmaps with transparent parts). The first level displays well, but when switching to the second level, pixel images from the first level can still be seen behind the new ones (where the transparent map was transparent).
I tried a few things to remove old widgets. (a) I tried to remove the QGridLayout and create a new instance, but then I found out that deleting the layout does not delete the widgets added to it. (b) I tried calling QLabel :: clear () on the new pixmaps, but this, of course, only affected the new ones, not the zombies. (c) I even tried to delete my m_view and m_scene and restore them every time I displayed a new level, but still no luck.
Then (d) I tried one of the solutions above, namely
QLayoutItem *wItem; while (wItem = widget->layout()->takeAt(0) != 0) delete wItem;
but that didn't work either.
However, googling further, I found an answer that worked . What was missing in (d) was a call to delete item->widget() . Now the following works for me:
// THIS IS THE SOLUTION! // Delete all existing widgets, if any. if ( m_view->layout() != NULL ) { QLayoutItem* item; while ( ( item = m_view->layout()->takeAt( 0 ) ) != NULL ) { delete item->widget(); delete item; } delete m_view->layout(); }
and then I create a new QGridLayout, as in the first level, add new level widgets to it, etc.
Qt is a lot different in many ways, but I think these problems show that it might be a little easier here.