jsk
jsk

Reputation: 197

How do I make a QML rectangle spawn?

I'm currently making a game called Snowflake to learn how to program QML with Javascript.

The only files i got besides that is a default qmlproject file and a png file.

I have made this timer(Timer) and a rectangle(skullflake) which it should spawn for every interval it has finished.

Timer { //spawnrate
         interval: 2000; running: true; repeat: true
         onTriggered: Qt.createQmlObject(skullflake)
     }

But when I try to run it, it gives me the error:

file:///where/the/project/is/saved/Snowflake/Snowflake.qml:21: Error: Qt.createQmlObject(): Invalid arguments

I have tried with both these elements but I can't seem to make it work

  • Qt.createComponent(skullflake)

  • Qt.createQmlObject(skullflake)

Upvotes: 1

Views: 763

Answers (2)

DRAX
DRAX

Reputation: 32393

You were using wrong Qt.createQmlComponent(). It requires 3 parameters:

Qt::createQmlObject ( string qml, object parent, string filepath )

So it should look like something like this (parent should be id of element which should contain skullflake):

Timer { //spawnrate
         interval: 2000; running: true; repeat: true
         onTriggered: Qt.createQmlObject("YOUR skullflake QML CODE (NOT FILE PATH)", parent, "skullflake")
     }

Upvotes: 2

jsk
jsk

Reputation: 197

I solved it by using the Qt.createComponents() which requires you to use a QML file on the side or use the Component element.

 Item {
 id: container
 width: 300; height: 300

 function skullFlake() {
     var component = Qt.createComponent("Skullflake.qml");
     if (component.status == Component.Ready) {
         var flake = component.createObject(container);
         flake.color = "purple";
     }
 }

 Component.onCompleted: loadButton()
}

Timer { //spawnrate
     interval: 2000; running: true; repeat: true
     onTriggered: skullFlake();
}

Upvotes: 1

Related Questions