how to access properties of item inside loader obj

2019-09-16 13:54发布

问题:

I am using a qml Loader component to push a page dynamically into view. Now the page I push has various properties and I would like to access them from the Loader component itself. However, I am unable to create aliases to these properties. So, I have something like:

Loader {
    id: loginLoader
    source: "qrc:/pages/IdPinLoginPage.qml"

    property alias hasNavBar: loginLoader.item.hasNavBar
    property alias hasStatusBar: loginLoader.item.hasStatusBar
}

This results in Invalid alias target location. How can I redirect these properties to the parent level in the Loader component?

回答1:

I recommended you to use sourceComponent instead of source property of the Loader for assign/bind value to loaded item easily.
Also for access loaded item, you can use item property of the loader:

Loader {
    id: loader
    sourceComponent: Component {
        SampleItem {
            foo: 13         //assign values to loaded item properties
            bar: "aleyk!"
        }
    }
}

Text {
    text: loader.item.bar   //Access to loaded item properties
}

SampleItem.qml

import QtQuick 2.6

Item {
    property int foo: 0
    property string bar: "salam";
}