在 QML 中测量经过的时间 [英] Measuring elapsed time in QML

查看:48
本文介绍了在 QML 中测量经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下示例:我们有一个 Qt Quick Controls Button.用户在 5 秒内单击它两次.第一次按下 Button 后,QML Timer 会运行这 5 秒.我们想要测量两次点击之间经过的时间,精确到毫秒.

Let's consider the following example: we have a Qt Quick Controls Button. The user clicks it twice within 5 seconds. After pushing the Button for the first time, the QML Timer is running for these 5 seconds. We want to measure the time elapsed between two clicks, with a millisecond accuracy.

不幸的是,QML Timer 无法向我们显示经过的时间.

Unfortunately, the QML Timer can't show us the elapsed time.

正如在 BlackBerry 论坛上所建议的那样,可以比较日期.不过,这不是很方便,因为第一次点击可能发生在 31 Dec 2015, 23:59:55,第二次点击可能发生在 1 Jan 2016, 00:00:05code> 并且检查必须很复杂.

As suggested on the BlackBerry forums, it would be possible to compare the dates. This isn't very handy, though, since the first click might occur on 31 Dec 2015, 23:59:55 and the second on 1 Jan 2016, 00:00:05 and the check would have to be complex.

还有更好的选择吗?

推荐答案

如评论中所述,QML Timer 不适合您的特定需求,因为它与动画计时器同步(更多详细信息此处),因此其分辨率也取决于动画计时器.

As explained in the comments, QML Timer is not suitable for your specific needs since it is synchronized with the animation timer (further details here) and thus its resolution is dependent on animation timer as well.

@qCring 解决方案肯定令人满意,如果需要更高的精度或更好的性能,我更喜欢这种方法(另请参阅 这个答案以及底部关于提高精度的有趣链接).

@qCring solution is for sure satisfying and I would prefer such an approach, if an higher precision is needed or a better performance (see also this answer and the interesting link at the bottom about improving precision).

但是,根据您的要求, QML/JS 方法是完全可行的.在这种情况下,您可以利用 JavaScript Date,因为它易于计算经过的时间,使用getTime(),也是因为QML完全支持JSDate扩展带有一些有用的功能.

However, given your requirements, a pure QML/JS approach is perfectly feasible. In this case you can exploit JavaScript Date, both because it's easy to calculate elapsed time, using getTime(), but also because QML fully supports JS Date and also extends it with some useful functions.

这是一个简单的例子:

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.3

ApplicationWindow {
    width: 300
    height: 300
    visible: true

    property double startTime: 0

    ColumnLayout {
        anchors.fill: parent

        Text {
            id: time
            font.pixelSize: 30
            text: "--"
            Layout.alignment: Qt.AlignCenter
        }

        Button {
            text: "Click me!"
            Layout.alignment: Qt.AlignCenter

            onClicked: {
                if(startTime == 0){
                    time.text = "click again..."
                    startTime = new Date().getTime()
                } else {
                    time.text = new Date().getTime() - startTime + " ms"
                    startTime = 0
                }
            }
        }
    }
} 

这篇关于在 QML 中测量经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆