Search code examples
qmlrepeater

How to use QML Repeater for page indicator?


Below is part of my code. It's working fine, however I spent a lot of time trying to solve it with Repeater to be more elegant and flexible, but couldn't.

Could you please suggest a solution to me? The areaMachine is in an other qml file.

Row {
        id: pageIndicatorBoxes
        anchors.centerIn: pageIndicatorLine
        spacing: 5

        Rectangle {
            id: pageIndicatorBox1
            width: 10
            height: 10
            color: areaMachine.page == 1 ? "#e5e5e5" : "#404040"
        }

        Rectangle {
            id: pageIndicatorBox2
            width: 10
            height: 10
            color: areaMachine.page == 2 ? "#e5e5e5" : "#404040"
        }

        Rectangle {
            id: pageIndicatorBox3
            width: 10
            height: 10
            color: areaMachine.page == 3 ? "#e5e5e5" : "#404040"
        }

        Rectangle {
            id: pageIndicatorBox4
            width: 10
            height: 10
            color: areaMachine.page == 4 ? "#e5e5e5" : "#404040"
        }
    }

Solution

  • Looks like you haven't look into the documentation about Repeater and its main delegate property. There you can find code examples that fits your problem, so you can combine it and have something like:

      Row {
        id: pageIndicatorBoxes
        anchors.centerIn: pageIndicatorLine
        spacing: 5
        
        Repeater {
          model: 4
          Rectangle {
            id: pageIndicatorBox1
            width: 10
            height: 10
            color: (areaMachine.page === (index + 1)) ? "#e5e5e5" : "#404040"
          }
        }
      }