How to pass properties to a Loader created object?

Basti An picture Basti An · May 30, 2017 · Viewed 7.1k times · Source

I have a QML Loader which loads another qml

Loader { id: gaugeLoader }

PieMenu {
    id: pieMenu

    MenuItem {
        text: "Add Bar Gauge"
        onTriggered: gaugeLoader.source = "qrc:/Gauges/horizontalBarGauge.qml"
    }
    MenuItem {
        text: "Action 2"
        onTriggered: print("Action 2")
    }
    MenuItem {
        text: "Action 3"
        onTriggered: print("Action 3")
    }
}

How can I pass parameters to set the ID, width, height and so on of the loaded qml?

Answer

m7913d picture m7913d · May 30, 2017

Method 1: Loader::setSource

You can use the Loader::setSource(url source, object properties) function to set the properties during construction, for example:

gaugeLoader.setSource("qrc:/Gauges/horizontalBarGauge.qml", {"width": 100, "height": 100});

Note that you cannot set the id attribute in this way, because it is a not an ordinary property attribute:

Once an object instance is created, the value of its id attribute cannot be changed. While it may look like an ordinary property, the id attribute is not an ordinary property attribute, and special semantics apply to it; for example, it is not possible to access myTextInput.id in the above example.

Instead, you can create a property alias as follows:

property alias gauge: gaugeLoader.item

Method 2: geometry relative to Loader object

As an alternative, you can set the width and height on the Loader object and specify the width and height in horizontalBarGauge.qml relative to its parent, i.e. the Loader object.

property alias gauge: gaugeLoader.item
Loader { 
    id: gaugeLoader 
    width: 100
    height: 100
}

qrc:/Gauges/horizontalBarGauge.qml:

Item {
    anchors.fill: parent
}