Issue in accessing a property with a loader in qml
-
Hi Team,
I am a basic learner in QML. I am facing an issue in accessing a property with a loader.
I am getting an error like below
"TypeError: Cannot read property 'rectId' of null"But from the Qt doc, I came to know, we can access an object property defined in another qml via loader's item property.
But in my sample program, I am not able to access an rectId object's property.
Can someone please correct me.Below is my sample code
main.qmlWindow { width: 640 height: 480 visible: true title: qsTr("Hello World") // Loader is defined in main.qml Loader { id: mainloader source: "qrc:/sample.qml" } }
sample.qml
Item { id: sampleId width: 100 height: 100 Rectangle { id: rectId property int val: 1 anchors.fill: parent color: "red" } Component.onCompleted: { console.log("Trying to access rectId property through Loader's item = ", **mainloader.item.rectId.val**) } }
-
Mmm, why do you want to access loader item properties inside the same item component? I mean Sample.qml, as a standalone component, should not know if it going to be called by a Loader, Stackview, etc.
First, in your example in the console.log line you just use rectId.val, not mainloader.item.rectId.val.
Second if want to use the properties of your item used in the Loader, you must expose as alias the Rectangle or as a property the val variable
sample.qml
Item { id: sampleId width: 100 height: 100 property alias rectIdAlias: rectId // First mode property int valExposed: rectId.val // Second mode Rectangle { id: rectId property int val: 1 anchors.fill: parent color: "red" } Component.onCompleted: { console.log("Trying to access rectId property = ", rectId.val) } }
main.qml
Window { width: 640 height: 480 visible: true title: qsTr("Hello World") // Loader is defined in main.qml Loader { id: mainloader source: "qrc:/sample.qml" onStatusChanged: if (loader.status == Loader.Ready) { console.log("Trying to access rectId property through Loader's item from main with Alias = ", mainloader.item.rectIdAlias.val) console.log("Trying to access rectId property through Loader's item from main with property = ", mainloader.item.valExposed) } } }
Hope this clarify your doubts.