其他分享
首页 > 其他分享> > c – 如何删除有一些子项作为成员的QGraphicsItem?

c – 如何删除有一些子项作为成员的QGraphicsItem?

作者:互联网

我有一个继承QGraphicsItem的自定义项.它有一些子图形项作为成员变量.我应该从哪个顺序删除场景中的这些项目以及如何删除它们?

解决方法:

像这样创建您的成员图形项:

class MyClass : public QGraphicsItem
{
    ...
private:

    SomeKindOfGraphicsItem* _item1;
    SomeOtherGraphicsItem* _item2;
}
MyClass::MyClass( ... ) :
    QGraphicsItem( ... ),
    _item1( new SomeKindOfGraphicsItem( ..., this ) ),
    _item2( new SomeOtherGraphicsItem( ..., this ) )
{
    ...
}

在这种情况下,仅从场景中删除父项(在此示例中为MyClass)就足够了.这将删除所有子项:

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).

此外,当MyClass的一个对象被删除时,它将通过Qt机制删除它的所有子节点:

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.

标签:c,qt,qgraphicsitem
来源: https://codeday.me/bug/20190825/1724233.html