我想删除Qt3DWindow的根场景的所有根节点。它包含多个层次结构级别的节点。我想删除引用并删除对象。最简单的方法是什么?
答案 0 :(得分: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());
答案 1 :(得分: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);