Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML ListElement pass list of strings

Tags:

listview

qt

qml

I have a listview who's delegate has a repeater in it which is supposed to be populated by text. If the repeater's model property is hard coded this way:

model: ['String 1', 'String 2', 'String 3'];

It works perfectly by showing 3 items in the repeater's region.
However, I want to send such a list using a ListElement and this is what I tried:

ListElement{
    shape: "Circle"; colors: ['Red', 'Blue'];
}

Unfortunately this approach doesn't work and throws an error:

ListElement: cannot use script for property value

How many I achieve this? TIA

like image 809
Akash Agarwal Avatar asked Sep 10 '25 16:09

Akash Agarwal


1 Answers

You can't:

Values must be simple constants; either strings (quoted and optionally within a call to QT_TR_NOOP), boolean values (true, false), numbers, or enumeration values (such as AlignText.AlignHCenter).

The most powerful way to expose data to views is by creating a C++ model.

However, if you really don't want to go to C++, you could store the colours in a comma-separated string, and then split them:

import QtQuick 2.6
import QtQuick.Window 2.0

Window {
    visible: true
    width: 200
    height: 200

    ListView {
        width: 32
        height: 64
        anchors.centerIn: parent
        model: ListModel {
            ListElement{
                shape: "Circle"
                colors: "red, blue"
            }
            ListElement{
                shape: "Square"
                colors: "green,yellow"
            }
        }
        delegate: Rectangle {
            width: 32
            height: 32
            radius: shape === "Circle" ? width / 2 : 0

            property var colorArray: colors.split(",")

            gradient: Gradient {
                GradientStop {
                    position: 0
                    color: colorArray[0]
                }
                GradientStop {
                    position: 1
                    color: colorArray[1]
                }
            }
        }
    }
}

screenshot

like image 50
Mitch Avatar answered Sep 13 '25 07:09

Mitch