Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

setProperty value by object and propertyname



  • Hey guys,

    I have the following problem:
    I want to create a textEdit-component which implements a two-way binding.

    Lets say I have a c++ object with several Q_PROPERTYs.
    Now I need a textEdit for each of this properties with a two way binding.
    Normally I can do something like this for each text Element:

    1. 
    TextInput: {
        id: t1
        ...
        onTextChanged: myObject.setText1(text)
    }
    
    Connections {
        target: myObject
        onTextChanged1: t1.text = myObject.text1
    }
    

    My idea is to pass an object and a property name to a custom TextInput.
    So I want to do all the other handling inside my custom component.

    CustomComponent {
        target: targetObject
        property: text1
    }
    

    How can I set a property by name and object in qml?
    Is there a function like setProperty(object, "property") within qml?

    CU
    mts



  • @themts said in setProperty value by object and propertyname:

    How can I set a property by name and object in qml?
    Is there a function like setProperty(object, "property") within qml?

    object[property] = value works, where property is a string representation of the property name.
    eg: t1["text"] = myObject.text1


  • Moderators

    @themts

    Is there a function like setProperty(object, "property") within qml?

    AFAIK no such way in QML. But if CustomComponent is a registered C++ class then you can use setProperty function for that object.



  • Hi

    I could find a solution that is working for me quite well:

        property alias target : targetBinding.target
        property alias property : targetBinding.property
    
        Binding {
            id: targetBinding
        }
    
        Binding {
            id: sourceBinding
            target: item1
            property: "text"
            value: (item1.property != "") && (item1.target != undefined) ? item1.target[item1.property] : ""
        }
    
        onEditingFinished: {
            if (property == "")
                return;
    
            targetBinding.value = text;
        }
    

    It would be nice if qt will get a built-in two way binding in future (see wpf).

    CU



  • @themts said in setProperty value by object and propertyname:

    It would be nice if qt will get a built-in two way binding in future (see wpf).

    You're not alone in this wish.


Log in to reply