Question

Row {
     Rectangle { width: 10; height: 20; color: "red" }
     Repeater {
         model: 10
         Rectangle { width: 20; height: 20; radius: 10; color: "green" }
     }
     Rectangle { width: 10; height: 20; color: "blue" }
 }

Here I want the color of each middle rectangle to be selected from a list. i.e. Each color has to be different rather than all being green.

Do I need nested repeaters? How should I go about this?

Was it helpful?

Solution

You can use index, as shown below, when model is just a number. And then you need to convert this number into a color, for example using Qt.rgba() or Qt.hsva() function, as shown below. The first repeater in code (adapted from here) will create a sliding hue for a rainbow effect.

If you just want to list colors as an array and use repeater to show them, the second repeater shows how to do this. Just set the array as the model, and use modelData in the repeater to access the value.

Row {
    Rectangle { width: 10; height: 20; color: "red" }

    // use index (values 0..9) to generate "rainbow"
    Repeater {
        model: 10
        Rectangle {
            width: 20; height: 20; radius: 10
            color: Qt.hsla(index/(10-1), 1, 0.5, 1)
        }
    }

    // use modelData to get color string from model
    Repeater {
        model: [ "#808080", "#1100F0", "#F20F20", "#F3F620" ]
        Rectangle {
            width: 20; height: 20; radius: 10
            color: modelData
        }
    }

    Rectangle { width: 10; height: 20; color: "blue" }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top