Detailed property alias in QML

QML alias attributes similar to C ++ reference to the general definition of different attributes, attribute aliases need to allocate new memory space, but the properties of the new declaration (called alias attribute) as an attribute that already exists (is alias attributes) of a direct reference, in other words, we have to attribute that already exists define an alias, use this property again in the future when they can access it through this property alias. A similar declaration declaration and attributes attribute alias, but need to use the alias instead of the keyword attribute type, and the right side of the property declaration must be a valid alias reference. The syntax is as follows:

property alias<name> : <alias reference>

The difference is that with common attributes, alias properties can only be a reference to an object whose declaration at the scope of the type or properties of an object, it can not contain any JavaScript expression, nor refer to objects outside the scope of the type. In addition, when the first declaration alias, alias reference must be provided, which is referenced in C ++ and is also very similar.

When using an alias attribute, you need to pay attention to the following points:

(1) In the alias attribute after the entire assembly is available initialized: thus a more common error code is performed from the downward is pointed when referring to the attribute not initialized on the use of an alias.

(2). You can not use another alias alias declared in the same assembly.

(3). Alias ​​attributes may be the same name as an existing attribute, but overrides existing attribute.

As shown in the following example:

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("QML语法")
    Rectangle{
        id:coloredRectangle
        property alias color: blueRectangle.color
        color: "red"
        Rectangle{
            id:blueRectangle
            color:"#1234ff"
        }
       Component.onCompleted:{
           console.log(coloredRectangle.color)
           setInternalColor()
           console.log(coloredRectangle.color)
           coloredRectangle.color = "#884646"
           console.log(coloredRectangle.color)

       }

       //内部函数访问内部属性
       function setInternalColor(){
           color = "#111111"
       }
    }
}  

Print Results:

 

 

Rectangle code declares a color alias attribute, its name and built Rectangle: when the same color property, any object using the reference color component attributes (e.g. coloredRectangle.color code) is aliasing, and not an ordinary Rectangle: color attribute, but the use of color properties directly in the internal components, reference is defined by real property, rather than an alias.

Guess you like

Origin www.cnblogs.com/QingYiShouJiuRen/p/11585670.html