Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML Access object property by property name string

Tags:

qt

qt5

qml

qtquick2

I want to create a QML binding in a repeated component. I want to bind the value of one of the elements to a property from a known object. My problem is that the name of said property that I want to bind to will be provided as a string in the component. How can I resolve the property name to an actual property that can be used as the value in a binding?

PS. If possible I guess I could pass the property directly to the repeater but then I would like to be able to convert the property to a string because I need both and don't want to pass both.

EDIT: Here's what I want:

    ListModel {
        id: settingsModel
        ListElement { title: "Bed Width"; setting: "bedWidth"; }
        ListElement { title: "Bed Length"; setting: "bedLength"; }
    }

    Component {
        id: settingsDelegate

        Item {
            width: parent.width
            height: childrenRect.height

            Label {
                id: setLabel
                text: title + ":"
                width: parent.width
            }

            TextBox {
                id: setTBox
                anchors.top: setLabel.bottom
                anchors.topMargin: 5
                width: parent.width

                Binding on text {
                    when: !setTBox.isActive
                    value: settings.setting
                }

                Binding {
                    target: settings
                    property: setting
                    value: setTBox.text
                }
            }
        }
    }

    Column {
        id: settingsColumn
        spacing: 10
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: txtSave.bottom
        anchors.topMargin: 15

        Repeater {
            model: settingsModel
            delegate: settingsDelegate
        }
    }
like image 262
Gerharddc Avatar asked Feb 15 '26 22:02

Gerharddc


1 Answers

My problem is that the name of said property that I want to bind to will be provided as a string in the component. How can I resolve the property name to an actual property that can be used as the value in a binding?

If you look at the documentation for Binding you will discover that the property property expects a string - property : string

So you don't have anything to resolve, that happens internally.

my problem is the "value: settings.setting" line

You could try something like settings[setting]

like image 93
dtech Avatar answered Feb 20 '26 06:02

dtech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!