QML component scope puzzle

后端 未结 2 1859
轻奢々
轻奢々 2021-02-14 10:58

Take this code:

import QtQuick 1.1

Rectangle {
    width:  100
    height: 100

    property color fromColor: \"red\"
    property color toColor:   \"blue\"

           


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 11:47

    Also see this:

    import QtQuick 1.1
    
    Item {
        property string s: "outer"
    
        Item {
            property string s: "middle"
    
            property Item it: Item {
                property string dummy: function() { console.log("(5) s: "+s); "" }()
                Component.onCompleted: console.log("(1) s: " + s)
            }
    
            Item {
                property string dummy: function() { console.log("(4) s: "+s); "" }()
    
                function f() {
                    console.log("(2) s: " + s)
                }
    
                Component.onCompleted: {
                    console.log("(3) s: " + s)
                    f()
                }
            }
        }
    }
    

    this code outputs:

    (5) s: outer
    (4) s: outer
    (3) s: outer
    (2) s: outer
    (1) s: outer
    

    Note, that however (to the Children property or not) and whatever (an Element or a javascript code snippet) we bind, the "middle" property is never found.

    The name lookup thus is:

    1. id's defined within the Item or Component (see 3)
    2. Local properties
    3. Top-level Item's properties (or Component, in case it's defined inline, even when the "Component" name is omitted, like when delegates are conveniently defined).

    Also, when a property is referenced within the component, but not defined within it, it still can be introduced within the "customized" component, and be seen:

    //OverrideInner.qml
    import QtQuick 1.1
    
    Item {
        Component.onCompleted: console.log(s)
    }
    

    .

    //OverrideOuter.qml
    import QtQuick 1.1
    
    Item {
        property string s: "overriden-outer"
    
        Item {
            property string s: "overriden-middle"
    
            OverrideInner {
                property string s: "overriden-inner"
            }
        }
    }
    

    Running "OverrideOuter.qml" produces:

    overriden-inner
    

    Again, see Martin's comments and the docs to clarify the matter. The relevant docs are:

    • Declarative Scope
    • Property Binding

提交回复
热议问题