在 QML 中测量组件移动的时间

Measure the time for a component movement in QML

在这个简单的代码中,用户可以向上或向下拖动 球拍。我们想知道 racket 运动的时间(即,onYChanged[=27 捕获的球拍的每个 y 变化=]) 。如果用户快速移动它,每个 y 变化的时间自然会比他们缓慢移动它的时间少。

我去了这个,但它总是写 "Time = 0"!请问有什么方法可以完成这个简单的任务吗?

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
    }
}

如果要测量变化时间,必须和Y做同样的步骤,将最后一次保存在内存中:

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
    }
}