首页 > 解决方案 > QT QML如何将毫秒转换为时间hh:mm:ss:zzz?

问题描述

QT QML 中是否有一个简单的函数可以将毫秒转换为格式为 hh:mm:ss:zzz 的用户可读时间?我找到了 tis 文档https://doc.qt.io/qt-5/qml-qtqml-date.html但我真的不明白如何在我的情况下使用它。到目前为止,这是我的代码,但它只显示秒和毫秒。

import QtQuick 2.8
import QtQuick.Controls 2.1


Rectangle {
id: mapItem
anchors.fill: parent

property int count: 0


    Timer {
      id: timer
      interval: 100
      running: true
      repeat: true
      onTriggered: count += 1
    }

    Text {

    text: (count / 10).toFixed(3)
    font.pixelSize: 20
    font.bold: true
    font.family: "Eurostile"}
 }

标签: datetimeqml

解决方案


Felgo Web Editor上测试,我已经按照预期格式化了计数器,请参见下文!

import Felgo 3.0
import QtQuick 2.5

App {
    id: app

    Rectangle {
        id: mapItem            
        property int count: 0
        Timer {
            id: timer
            interval: 10 // i set to 10 for testing for faster results, but worked on 100 also
            running: true
            repeat: true
            onTriggered: time.text = new Date(mapItem.count += 1).toLocaleTimeString(Qt.locale(), "hh " + "mm " + "ss " + "zzz") // you can change the formatting as you please
            }

        Text {
            id: time
            font.bold: true
            font.family: "Eurostile"
        }
    } 
}

请记住,如果您正在格式化日期,您将替换为toLocaleTimeStringtoLocaleDateString任何最适合每个用例的内容。

更新!如果您正在寻找实时计数,您可能还想将时间间隔更改为count += 1+= 16除非计时器不适用于实时秒数

希望这可以帮助!


推荐阅读