Home > Enterprise >  Dynamic property name assignments inside delegate
Dynamic property name assignments inside delegate

Time:11-21

I am trying to include a Settings object inside the delegate of a Repeater so that I can save the value of a SpinBox. However, I can't figure out how to dynamically set the property alias name.

What I want to achieve is to have the property alias name to be the same as the modelData. For example, for item1: "property alias item1: box.value"; for item2: "property alias item2: box.value", etc.

Column {
    Repeater {
        model: ["item1", "item2", "item3", "item4", "item5"]
        delegate: RowLayout {
            Settings {
                fileName: "config"
                category: modelData
                property alias value: box.value
            }
            Label {
                text: modelData
            }
            SpinBox {
                id: box
            }
        }
    }
}

The code above generates the following settings, and is a work around to what I wanted to do:

[item1]
value=""
[item2]
value=""
[item3]
value=""
...

What I want is a single category with the values, like so:

[category]
item1=""
item2=""
item3=""
...

CodePudding user response:

For this case you cannot use properties but the value() and setValue() methods:

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Qt.labs.settings

ApplicationWindow {
    width: 640
    height: 480
    visible: true

    readonly property var values: ["item1", "item2", "item3", "item4", "item5"]
    Settings {
        id: settings
        category: "category"
    }

    Column {
        Repeater {
            model: values
            delegate: RowLayout {
                id: row_layout
                Label {
                    text: modelData
                }
                SpinBox {
                    id: box
                }
                Component.onCompleted: box.value = settings.value(modelData, 0)
                Component.onDestruction: settings.setValue(modelData, box.value)
            }
        }
    }
}

Output:

[category]
item1=6
item2=6
item3=4
item4=2
item5=2
  • Related