3
votes

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
Note that adding them as members doesn't mean they are children in the sense Qt defines this relation. You have to set a parent in the going-to-be-children items, namely yourself (this), either in the constructor or afterwards with childItem->setParent(this).leemes
They are member variables and takes the main item as a parent.fatma.ekici
Then everything is fine. But this comment might be of importance for future readers, as it might be a mistake one can do easily.leemes

1 Answers

7
votes

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.