How to delay JavaScript action within QML?

Benoit picture Benoit · Jul 11, 2012 · Viewed 7k times · Source

I am building a C++ application based on QML.

To make it simple :

In my main QML file, I have a button (Rectangle) calling a JavaScript function (defined in an external JS file) when clicked:

// My JS file linked to the main QML window
[...]
function actionOnButtonClicked()
{
    var x = 0;
    var y = 0;
    for(var i = 0; i < 3; i++)
    {
        createObject(x, y);
        x = x + 10;
        y = y + 10;
    } 
}

As you can see, in this function, I call n (= 3 here) times another JS function to dynamically create several QML objects to add to the scene:

function createObject(xPosition, yPosition)
{
    component = Qt.createComponent("Symbol.qml");
    component.createObject(windowApp, {"x": xPosition, "y": yPosition});
}

This is working fine. But the created object (Symbol) appears in the windowApp with a translation animation (around 1sec.), and I would like to wait for the first object's animation to complete before creating the second one...

As we cannot use setTimeOut() JavaScript function in QML, I wonder how I could achieve this. I do not see how I could make use of the QML Timer object or even PauseAnimation...

Does somebody know how to add a delay between 2 QML JavaScript operations ?

Answer

Redanium picture Redanium · Jul 16, 2016

I think this QML Timer type can help you achieve what you want.

import QtQuick 2.0
Item {
       Timer {
               interval: 500; running: true; repeat: true
               onTriggered: time.text = Date().toString()
             }

       Text { id: time }
}