QML Loader: Access property from loaded file.
-
Hi!
I want to change a value in a loaded file. A minimal example based on QtCreators (changes are commented) template looks like this:
//main.qml import QtQuick 2.5 import QtQuick.Window 2.2 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") //added an alias for loader: property alias itemLoader: myLoader.item MouseArea { anchors.fill: parent onClicked: { //added: myLoader.source and itemLoader.myValue myLoader.source="file.qml" itemLoader.myValue=12 console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"')) } } TextEdit { id: textEdit text: qsTr("Enter some text...") verticalAlignment: Text.AlignVCenter anchors.top: parent.top anchors.horizontalCenter: parent.horizontalCenter anchors.topMargin: 20 Rectangle { anchors.fill: parent anchors.margins: -10 color: "transparent" border.width: 1 } } //added Loader: Loader { id: myLoader } }
//file.qml import QtQuick 2.0 import QtQuick.Controls 1.4 Item { id:toLoad anchors.fill: parent Rectangle { height: 20 width: 20 color: "red" property int myValue:0 SpinBox { id: spin value: myValue } } }
What did I do wrong?
Thanks for your help :) -
The variable "myValue" is not accessible outside the file.qml since it was defined in the child element of root item in file.qml, you should make an ailas in root item of file.qml
Item { id:toLoad anchors.fill: parent //1. Aded alias here property alias myValue: rect.myValue Rectangle { //2. Added id to access property id: rect height: 20 width: 20 color: "red" property int myValue:0 SpinBox { id: spin value: myValue } } }
Actually it is not good idea to make these call at the same place
myLoader.source="file.qml" itemLoader.myValue=12
First line initiates loading of the file. There is no guarantee that item will be loaded immidiately. So you should change dynamically loaded properties only after loader finish loading, you can just subscribe on the signal
Connections{ target: myLoader onLoaded:{ console.log("Loaded"); itemLoader.myValue=12; console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"')) } }
-
@Dmitiy-Tyugin
Thank you! Now it works and I thank you for your suggestion and the explanation with the Connections! I will take heed of it.