Zhas Nurushev
Zhas Nurushev

Reputation: 55

How to modify QML dynamic objects from JavaScript

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

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

From other QML form I load this button via Qt.createComponent method:

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

I tried to set/get width of moduleButton:

moduleButton.width = 30;

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

How to access dynamic object attributes and child elements?

P.S. Qt.createQmlObject method perfectly works, but I need to load QML from file, not from string.

Upvotes: 3

Views: 3710

Answers (1)

Armaghast
Armaghast

Reputation: 753

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

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

myButton.width = 40

The moduleButton is a component (a factory), used to instantiate the item.

Documentation: Dynamic QML Object Creation from JavaScript

Upvotes: 5

Related Questions