Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid creating a property binding on initialization in QML?

Tags:

qt

qml

I want to create a custom QML component with two properties one and two, which should have default values when left uninitialized. In particular, if two should get an initial value depeding on one. The following code

Rectangle {
  property int one: 1
  property int two: 2 * one
}

however creates a property binding: Whenever one changes, two is updated to the new value of 2 * one. How can I initialize two to the value of 2 * one without creating a binding?

like image 240
Tobias Avatar asked Oct 23 '13 20:10

Tobias


2 Answers

A way to explicitly tell that you don't want a binding is to call an assignment in an expression block:

Rectangle {
  property int one: 1
  property int two: {two = 2 * one}
}

Unlike the approach of breaking the binding in onCompleted, the expression block avoids the creation and then destruction of a binding object, and it looks cleaner.

like image 172
David Foley Avatar answered Oct 14 '22 06:10

David Foley


Explicitly break the binding upon component completion:

Rectangle {
    property int one: 1
    property int two: 2 * one
    Component.onCompleted: two = two
}

The two = two assignment breaks the binding and two is no longer updated as one changes.

like image 8
pixelgrease Avatar answered Oct 14 '22 06:10

pixelgrease