Reputation: 303540
Say I have a QML Application with a toolbar:
ApplicationWindow {
header: MyTools {
showAdminButtons: userIsAdmin()
}
}
I can dynamically pick the component to show by using a Loader
:
ApplicationWindow {
header: Loader {
source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
}
}
However, if I want to supply custom property values to that component (like showAdminButtons
above), I must use the setSource()
method:
ApplicationWindow {
header: Loader {
Component.onCompleted: {
var qml = Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml";
setSource( qml, {showAdminButtons:userIsAdmin()} );
}
}
}
Is there a "QML-only" way to supply properties to a Loader, that does not require Component.onCompleted
? (I cannot fully justify why Component.onCompleted
feels like a gross hack workaround to me, but it does, every time I have to use it. It's something to do with the declarative nature of QML vs. the procedural nature of JS.)
Upvotes: 2
Views: 1985
Reputation: 3369
Method 1: binding (or a simple assignment if binding is not necessary) when Loader.onLoaded
:
ApplicationWindow {
header: Loader {
source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
onLoaded: {
item.showAdminButtons = Qt.binding(function() { return userIsAdmin(); }
}
}
}
Method 2: use Binding
type:
ApplicationWindow {
header: Loader {
id: loader
source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
Binding {
target: loader.item
property: "showAdminButtons"
value: userIsAdmin()
}
}
}
Upvotes: 6