I want to delete all root nodes of the root scene of a Qt3DWindow. It contains multiple hierarchy levels of nodes. I want to remove the references and delete the objects. What is the simplest way to do that?
Asked
Active
Viewed 1,431 times
1
-
1Why not delete it like any other container in C++? Iterate through every object you want to delete, change properties you need ("removing references") and store references to those objects in some kind of list. In the next step iterate through every item on the list and delete it. In the end clear the list. Or make the function recursive (like in [this post](https://stackoverflow.com/a/17178168/5163799)) to omit usage of the list. – Filip Hazubski Aug 18 '17 at 14:47
-
That works. It is a few lines of code (not just one), but it works. Thanks! – Codev Aug 18 '17 at 15:17
-
@Codev Consider posting your solution as a answer. – m7913d Aug 18 '17 at 19:16
2 Answers
1
I used this recursive function to do it:
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;
}
}
It deletes all QEntity and its QComponent objects recursively.
Usage:
Qt3DCore::QEntity* rootEntity = new Qt3DCore::QEntity();
view->setRootEntity(rootEntity)
...
deleteChildrenRecursively(rootEntity->childNodes());

Codev
- 1,040
- 2
- 14
- 31
-
`node->childNodes` signature has changed to const. You may want to update this to take a const reference. – Alex Baum Jun 28 '23 at 22:03
0
The @Codev 's answer is reasonable but it crashed on my application with Qt Version 5.12.2. So I rewrite the recursive method and it works.
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;
}
usage:
Qt3DCore::QEntity* entity = new Qt3DCore::QEntity();
...
delete_entity_recursively(entity);