在下面的例子中,application.qml创建了SelfDestroyingRect.qml组件的5个实例,每一个实例运行一个NumberAnimation,当动画结束时在其根对象上调用destroy()来进行自我销毁。
myjs.qml
import QtQuick 2.2
Item {
id: container
width: 500; height: 100
Component.onCompleted: {
var component = Qt.createComponent("SelfDestroyingRect.qml");
for (var i=0; i<5; i++) {
var object = component.createObject(container); //container为父对象
object.x = (object.width + 10) * i;
}
}
}
SelfDestroyingRect.qml
import QtQuick 2.2
Rectangle {
id: rect; width: 80; height: 80; color: "red"
NumberAnimation on opacity {
to: 0; duration: 1000
onRunningChanged: {
if (!running) {
console.log("Destroying...")
rect.destroy();
}
}
}
}
知识点:
动态删除对象(书P79)、从JavaScript动态创建QML对象(书P77)