Take this code:
import QtQuick 1.1
Rectangle {
width: 100
height: 100
property color fromColor: "red"
property color toColor: "blue"
gradient: Gradient {
property color fromColor: "yellow"
property color toColor: "green"
GradientStop { position: 0; color: fromColor }
GradientStop { position: 1; color: toColor }
}
}
Why exactly does the Gradient pick its fromColor and toColor properties from the enclosing element?
Where is this documented (at least within source code comments, better within the official docs)?
Note: this “QML obfuscation example is from Girish Ramakrishnan’s talk Qt Quick Best Practices and Design Patterns (rewind to 25th minute), where he does say that the thing is extremely complicated and has to with component scope and like that, but has no time to explain why.
[UPDATE]
So, as MartinJ tells below, the top-level component in the element-property (not only element-child) hierarchy has its properties visible to all properties however deep nested, with the precedence being of that properties’ properties, and all properties of “intermediate” items not seen at all.
Here’s a small example:
import QtQuick 1.1
Item {
Item {
property string s: "parent-str"
Item { Component.onCompleted: console.log(s) }
}
}
This gives: "ReferenceError: Can't find variable: s"
And this works as expected:
import QtQuick 1.1
Item {
property string s: "parent-str"
Item { Component.onCompleted: console.log(s) }
}
, outputting "parent-str".
Please see MartinJ’s comments below.
This certainly doesn’t look intuitive at first glance, but comment out
fromColorandtoColorin the component root item and the reason becomes apparent. From the QML Scope docs you can see that the scope includes:id‘s defined within the Component.A
GradientStop {}in the example above has no local properties defined. The root component does, and they are the properties thatfromColorandtoColorresolve to. The properties inGradient {}are not in the scope of theGradientStop {}at all.