1
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?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • When you copy-paste code from somewhere, it'd be polite to link to the source, in this case in [Qt docs](http://qt-project.org/doc/qt-5.1/qtquick/qml-qtquick2-repeater.html) – hyde Mar 01 '14 at 09:14
  • @hyde I usually do it when code is somewhat big. Okay, will do it from next time for tiny codes also. – Aquarius_Girl Mar 01 '14 at 09:47

1 Answers1

2

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" }
}
hyde
  • 60,639
  • 21
  • 115
  • 176
  • 1
    @TheRebelAquarius YW. I improved the answer a bit, to cover the case of having colors in the model as array, and also changed the first case to use `hsva()`, which is often more convenient than `rgba()` for generating colors from numbers. – hyde Mar 01 '14 at 10:41