How can I add a property dynamically to a QML element?

I want to dynamically add properties to a QML element:

Item {
 id: dynamicProperty;
 property int first;


 Component.onCompleted: {
  /* once this block of code is executed, i want to add
     property int second; property bool third; property variant fourth;
  */
 }

}

Is there a way to accomplish the above task.

+5
source share
4 answers

I do not think QML was designed to support the creation of dynamic properties.

Depending on your use case, this could be handled using a "script instance" (I composed the term). Basically, each instance of a QML component that imports a script that does not have a statement .pragma librarywill work with its own copy of the globals declared in the script.

For example, you can look at the PageStack (qt-components) code page .

import "PageStack.js" as Engine, , , , .

QML- , "script " .

+4

: , - , . , QML JavaScript, - , , .

, JS- . , .

MouseArea {
    anchors.fill: parent
    onClicked: console.log(rect.newProp)
}

Rectangle {
    id: rect
    width: 50
    height: 50
    x: 50
    y: 50
    color: 'green'

    MouseArea {
        anchors.fill: parent
        onClicked: { var obj = Object.defineProperty(rect, 'newProp',
                                                     {
                                                         enumerable: false,
                                                         configurable: false,
                                                         writable: false,
                                                         value: '50'
                                                     })}
    }
}

"undefined". "50".

+5

Maybe you can do it like this:

Item {
    id: dynamicProperty;
    property int first;
    property var extraData;

    Component.onCompleted: {
        /* once this block of code is executed, i want to add
           property int second; property bool third; property variant fourth;
        */
        var data;
        data["second"] = 0;
        data["third"] = false;
        ...
        extraData = data;
   }
}
0
source

I'm not sure if I can add dynamic properties to the qml object, buy one of the simplest forms, you can disable, hide or change the properties, if, for example:

if(manual==true)
{
    icon.visible=true
}
else {
    icon.visible=false
}

or you can create dynamic components of your element or change the view using the loader element.

-1
source

All Articles