Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display time automatically updating every minute

Tags:

qt

qml

I have an QML application in which I'm trying crate a simple clock that would show current time - similar as those in every operating system.

The time is supposed to be presented to the user as a text in format hh:mm, so i.e. 16:12.

Currently I'm trying a solution with a Timer component running during the application lifetime and updating the text by invoking:

timeText.text = Qt.formatTime(new Date(),"hh:mm")

every 60 seconds. Is there a better way to do this or using a Timer component is necessary.

Snippet with the whole code:

Text {
    id: timeText
    x: 10
    y: 10
    text: Qt.formatTime(new Date(),"hh:mm")
}

Timer {
    id: timer
    interval: 60000
    repeat: true
    running: true

    onTriggered:
    {
        timeText.text =  Qt.formatTime(new Date(),"hh:mm")
    }
}
like image 745
Mateusz Andrzejewski Avatar asked Mar 06 '14 16:03

Mateusz Andrzejewski


1 Answers

I realise this question is a few years old now, but no solution was given, so here's how I did it (this applies to SailfishOS);

Add a property;

    property alias updatesEnabled: timeText.updatesEnabled

Then, the important part;

    Item {
    id: timeText
    color: timeText.color
    font.pixelSize: Theme.fontSizeHuge * 2.0
    text: { updatesEnabled: timeText.time  <--------add line here
        Qt.formatTime(new Date(), "hh:mm:ss")
    }
    anchors {
        horizontalCenter: parent.horizontalCenter
    }
}

The above now keeps the time/date up-to-date. I played around inserting the code at different lines, but this was the only way I could get it to work.

like image 149
fmotl Avatar answered Oct 23 '22 15:10

fmotl