I have a custom item which inherits QGraphicsItem. It has some child graphics items as member variables. In which order should I remove these items from the scene and how to delete them?
1 Answers
Create your member graphics items like this:
class MyClass : public QGraphicsItem
{
...
private:
SomeKindOfGraphicsItem* _item1;
SomeOtherGraphicsItem* _item2;
}
MyClass::MyClass( ... ) :
QGraphicsItem( ... ),
_item1( new SomeKindOfGraphicsItem( ..., this ) ),
_item2( new SomeOtherGraphicsItem( ..., this ) )
{
...
}
In that case, it is sufficient to remove only the parent item (MyClass
in this example) from the scene. This will remove all child items as well:
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).
Also, when an object of MyClass
gets deleted, it will delete all of its children through Qt
mechanics:
QGraphicsItem::~QGraphicsItem() [virtual]
Destroys the QGraphicsItem and all its children. If this item is currently associated with a scene, the item will be removed from the scene before it is deleted.
Note: It is more efficient to remove the item from the QGraphicsScene before destroying the item.
this
), either in the constructor or afterwards withchildItem->setParent(this)
. – leemes