How to change dynamic QML objects from JavaScript

I have a QML file that describes a button (moduleButton.qml):

import QtQuick 2.0
Rectangle {
    id: button;
    width: 100; height: 20
    Text {
        id: buttonText;
        text: "Hello World";
    }
}

From another QML form, load this button using the Qt.createComponent method:

var moduleButton = Qt.createComponent("moduleButton.qml");
moduleButton.createObject(mainRect);

I tried setting / getting the width of the Button module:

moduleButton.width = 30;

But the following error was received: Cannot assign to non-existent property "width"

How to access attributes of dynamic objects and child elements?

PS The Qt.createQmlObject method works fine, but I need to load QML from a file, not from a string.

+3
source share
1 answer

createObject()returns a new object. Your code should look like this:

var moduleButton = Qt.createComponent("moduleButton.qml");
var myButton = moduleButton.createObject(mainRect);

myButton.width = 40

A Button module is a component (a factory) used to instantiate an element.

Documentation: http://qt-project.org/doc/qt-5/qtqml-javascript-dynamicobjectcreation.html

+5

All Articles