Search code examples
qtqmlqtquick2qt-quickqtquickcontrols2

Measure the time for a component movement in QML


In this simple code, the user can drag the racket up or downwards. We want to know the time for the racket movement (i.e, each y changes of the racket caught by onYChanged) . If the user moves it fast the time for each y change is littler than the time they move it slowly, naturally.

I went for this, but it always writes "Time = 0"! Is there any way for doing this simple task please?

main.qml:

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    id: window
    visible: true
    width: 700; height: 500
    color: "gray"

    Rectangle {
        id: table
        width: window.width / 1.15; height: window.height / 1.15
        y: 10
        anchors.horizontalCenter: parent.horizontalCenter
        color: "royalblue"
    }

    Racket {
        id: racket
        x: table.width - 10
        y: table.height / 2
    }
}

Racket.qml:

import QtQuick 2.12

Rectangle {
    width: 15; height: 65

    property int oldY: y
    property bool yUwards: false
    property bool yDwards: false
    property double colTime

    onYChanged: {
         colTime = new Date().getTime()

        if (y > oldY)
            yDwards = true
        else if (y < oldY)
            yUwards = true
        oldY = y
        console.log("Time = ", colTime - new Date().getTime())
    }

    MouseArea {
        anchors.fill: parent
        anchors.margins: -parent.height
        drag.target: parent
        drag.axis: Drag.YAxis
        drag.minimumY: table.y
        drag.maximumY: table.height - parent.height + 10
    }
}

Solution

  • If you want to measure the change time, you must do the same procedure as with Y, save the last time in memory:

    import QtQuick 2.12
    
    Rectangle {
        width: 15; height: 65
    
        property bool yUwards: false
        property bool yDwards: false
        property real oldY: y
        property double last_time: new Date().getTime()
    
        onYChanged: {
            var current_time = new Date().getTime()
            console.log("Time = ", current_time - last_time)
            if (y > oldY)
                yDwards = true
            else if (y < oldY)
                yUwards = true
            oldY = y
            last_time = current_time
        }
    
        MouseArea {
            anchors.fill: parent
            anchors.margins: -parent.height
            drag.target: parent
            drag.axis: Drag.YAxis
            drag.minimumY: table.y
            drag.maximumY: table.height - parent.height + 10
        }
    }