Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML Moving text with timer

Tags:

qt

qml

I need to create moving text on the screen continuously from right to left, I have implemented it using QML Timer and Text element.

The below code works fine but I am concerned about the below code causing more cpu or memory usage mainly because the timer is triggered every 33 ms. I have to use this in my places in my application and in multiple instances, like inside many grid windows.

Is this right approach? or does anything exist better than this?

Rectangle{
        width:parent.width
        height:parent.height
        color: "#333333"

        Timer {
            id: resetTimer
            interval: 33
            repeat: true
            running: true
            onTriggered: {
             console.log("triggred");
             moving_text.x = moving_text.x-1
             if(moving_text.x<-1*moving_text.paintedWidth)
               moving_text.x=parent.width
            }
        }

        Text{
            id:moving_text
            x:parent.width
            text:"Moving text"
            color: "white"
        }
    }
like image 420
Haris Avatar asked Mar 16 '26 08:03

Haris


1 Answers

Why to make things so complected. You could use NumberAnimation on x as follows:

import QtQuick 2.0

Rectangle{
    id: root
    width:250
    height:250
    color: "#333333"

    Text{
        id:moving_text
        x:parent.width
        text:"Moving text"
        color: "white"

        NumberAnimation on x{
            from: root.width
            to: -1*moving_text.width
            loops: Animation.Infinite
            duration: 3000
        }
    }
}

As for your concern about memory and cpu usage, you should compare both the methods and check which one suits you. But my personal recommendation is to use NumberAnimation.

like image 127
Vedanshu Avatar answered Mar 20 '26 03:03

Vedanshu