0
votes

If I had a rectangle with a property width, there are three options to set a value that I confuse:

read-only property int widthReadOnly: 200

Rectangle{
    width: 200                             //first 
    width: widthReadOnly                   //second
    Component.onCompleted: {width = 200}   //third
}

Could you tell me when to use each of them? Thank you.

1

1 Answers

1
votes

at first all of your examples do quite the same. First and second examle create a binding to the values, but beacause they are an int (first), or a read-only property (second) they will never change. Because there will never be a ...Changed() Signal, they are also like your third example whitch is only an assignment (if the assigned value changes, the change will not change the assignee).

The intendet use of the Bindings is when you bind to some value that is Changeable, maybe the width of the parent item. So if the parent width changes it will be propagated to the child item:

import QtQuick 2.0
import QtQuick.Controls 1.4
Item {
    Rectangle {
        id: papa
        width: 100
        height: 100
        color: "red"

        Rectangle {
            id: child
            anchors.centerIn: parent
            width: parent.width / 2
            height: parent.height / 2
            color: "lightsteelblue"
        }
    }
    Button {
        id: button
        onClicked: {
            papa.width = 100 + (Math.random() * 100)
        }
    }
}

As you see, if the papa width is updated, it also changes the width of the child item.