1

我想删除 Qt3DWindow 的根场景的所有根节点。它包含多个层次结构级别的节点。我想删除引用并删除对象。最简单的方法是什么?

4

2 回答 2

1

我使用这个递归函数来做到这一点:

void deleteChildrenRecursively(Qt3DCore::QNodeVector& vector)
{
    foreach(Qt3DCore::QNode* node, vector){
        Qt3DCore::QEntity* entity = (Qt3DCore::QEntity*)node;
        QList<Qt3DCore::QComponent*> componentsToDelete;
        foreach(Qt3DCore::QComponent* component, entity->components()){
            entity->removeComponent(component);
            delete(component);
            component = NULL;
        }
        deleteChildrenRecursively(node->childNodes());
        delete(node);
        node = NULL;
    }
}

它递归地删除所有 QEntity 及其 QComponent 对象。

用法:

Qt3DCore::QEntity* rootEntity = new Qt3DCore::QEntity();
view->setRootEntity(rootEntity)
...
deleteChildrenRecursively(rootEntity->childNodes());
于 2017-08-23T14:09:03.620 回答
0

@Codev 的答案是合理的,但它在我的 Qt 版本 5.12.2 的应用程序上崩溃了。所以我重写了递归方法并且它有效。

void delete_entity_recursively(Qt3DCore::QNode *node){
    Qt3DCore::QEntity* entity = dynamic_cast<Qt3DCore::QEntity*>(node);
    if(entity == nullptr){
        return;
    }
    auto components_to_delete = entity->components();
    foreach(auto *component,components_to_delete){
        entity->removeComponent(component);
        delete(component);
        component = nullptr;
    }
    auto children_nodes = entity->childNodes();
    foreach(auto *child_node, children_nodes){
        delete_entity(child_node);
    }
    delete entity;
    entity = nullptr;
}

用法:

Qt3DCore::QEntity* entity = new Qt3DCore::QEntity();
...
delete_entity_recursively(entity);
于 2019-05-23T06:33:33.563 回答