Search code examples
qtanimationtimerqmlqt-quick

Timer not working correctly


We have to make progress bar consisting with slider, which has colour transition as the slider proceeds as shown in the figure below.

Progress Bar

I tried my hand with below logic but could not get the desired effect. Any help or suggestion how to implement the same.

Below is my code snippet

import QtQuick 1.1

Rectangle {
    id: container

    width: 500; height: 400

    Row {
        id:repeaterid
        x: 75
        y: 280
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 114
        spacing: 4
        Repeater {
            model: 50
            Rectangle {
                id: smallrect
                color: "red"
                width:4
                height:4
            }
        }
    }

    Timer {
        id: progressTimer
        interval: 50
        running: true
        repeat: true
        onTriggered: {
            if (slider.x < 460)
            {
                slider.x += repeaterid.spacing + 4
                smallrect.color = "green"
            }
        }
    }

    Rectangle {
        id: slider
        x: repeaterid.x
        y: repeaterid.y
        width: 6; height: 6
        color: "blue"
    }
}

I have tried to use ColorAnimation, but got any luck.


Solution

  • To access the items within the repeater you can use the itemAt(index) function. This will allow you to change the color of the repeaters children. I also added a indexCurrent property to keep track of the current index.

    Try this code:

    import QtQuick 1.1
    
    Rectangle {
      id: container
    
      width: 500; height: 400
    
      property int indexCurrent: 0
    
      Row {
        id:repeaterid
        x: 75
        y: 280
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 114
        spacing: 4
        Repeater {
            id: repeater
            model: 50
            Rectangle {
                id: smallrect
                color: "red"
                width:4
                height:4
            }
        }
      }
    
      Timer {
        id: progressTimer
        interval: 50
        running: true
        repeat: true
        onTriggered: {
            if (slider.x < 460)
            {
                slider.x += repeaterid.spacing + 4
                repeater.itemAt(indexCurrent).color = "green"
                indexCurrent = indexCurrent + 1
            }
        }
      }
    
      Rectangle {
        id: slider
        x: repeaterid.x
        y: repeaterid.y
        width: 6; height: 6
        color: "blue"
      }
    }