Sprite.qml
import QtQuick 2.6
Rectangle{
width: 80;height: 50
color: "blue"
}
componentCreation.js
var component;
var sprite;
function createSpriteObjects(){
component=Qt.createComponent("Sprite.qml");
if(component.status==Component.Ready)
finishCreation();
else
component.statusChanged.connect(finishCreation);
}
function finishCreation(){
if(component.status==Component.Ready){
sprite=component.createObject(appWindow);
if(sprite==null){
console.log("Component.Error: ",sprite==null);}
else{
sprite.x=100;
sprite.y=200;
}
}
else if(component.status==Component.Error){
console.log("Component.Error: ",component.errorString());
}
}
main.qml
import QtQuick 2.6
import "componentCreation.js" as MyScript
Rectangle{
id:appWindow
width: 300;height: 300
Component.onCompleted:MyScript.createSpriteObjects();
}
SelfDestroyingRect.qml:
import QtQuick 2.6
Rectangle{
id:rect
width: 80;height: 50
color: "green"
NumberAnimation on opacity {
to:0
duration:3000
onRunningChanged: {
if(!running){
console.log("Destroying... ");
rect.destroy();
}
}
}
}
main.qml
Rectangle{
id:container
width: 300;height: 200
Component.onCompleted:{
var component=Qt.createComponent("SelfDestroyingRect.qml");
for(var i=0;i<5;i++){
var object=component.createObject(container)
object.x=(object.width+10)*i;
}
}
}
createQmlObject
var newObject = Qt.createQmlObject('import QtQuick 2.0; Rectangle {color: "red"; width: 20; height: 20}',
parentItem,
"dynamicSnippet1");