Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML component scope puzzle

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.

like image 268
mlvljr Avatar asked Jul 05 '12 07:07

mlvljr


1 Answers

This certainly doesn't look intuitive at first glance, but comment out fromColor and toColor in the component root item and the reason becomes apparent. From the QML Scope docs you can see that the scope includes:

  • all of the id's defined within the Component.
  • local properties
  • the properties of the root object of the Component

A GradientStop {} in the example above has no local properties defined. The root component does, and they are the properties that fromColor and toColor resolve to. The properties in Gradient {} are not in the scope of the GradientStop {} at all.

like image 112
MartinJ Avatar answered Sep 20 '22 03:09

MartinJ