PDA

View Full Version : Properly destroy a qml dynamic object derived from another item



john_god
1st September 2017, 07:05
Hi

I have a Physics.qml



Item {
id: root
.........
signal destroyBullet()
onDestroyBullet: {
console.log("destroy Physics.qml")
root.destroy()
}
...........
}

and a Bullet.qml


import QtQuick 2.0

Physics {
id: root
................
onDestroyBullet: {
console.log("destroy Bullet.qml")
root.destroy()
}
.........
}


Bullet is dynamically created, when is destroyed, do I need to call destroy() in both Bullet.qml and Physics.qml ? Or it's enought just to call destroy in Physics.qml, or in Bullet.qml?

wysota
1st September 2017, 07:30
You only need to destroy each object once. The context is not important as long as you call it on appropriate object.

john_god
1st September 2017, 22:45
Still a bit confused by your answer. Please note that Physics.qml is just a "template" for Bullet.qml, I'm only creating dynamic Bullet objects.
To me it's more convenient to call destroy in Physics.qml, because that's where I have all the logic,
so when you say context is not important you mean that I can destroy it from Physics context and remove the code related to destroy from Bullet.qml, right ?

wysota
3rd September 2017, 12:19
QML is like C++ in this regard - the object "id" is similar to a pointer in C++ where if you have access to the pointer you can call any of its public methods including the delete operator (regardless if it is a final class or not). Putting aside validity of the pattern where an object calls destroy() on itself as well as having a destroyBullet() signal in super-type of the bullet type, you can destroy it from within the base type.

Having said that it is more kosher to call destroy() on the bullet from outside the bullet object itself so that you can use Bullet for various things.

Component {
id: bulletComponent
Bullet {
id: bullet
SequentialAnimation on y {
NumberAnimation {
from: screen.height
to: 0
duration: 3000
}
ScriptAction { script: bullet.destroy() } // die after reaching y=0
}
}
}

// ...

var bullet = bulletComponent.createObject(someParent, { ... })

john_god
4th September 2017, 09:30
Thank you.