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?
Double check that there is not need to Binding and be careful about not making codes dirty.
You can fill property with value very soon as follows:
(I am not sure, you may be able to set initial value using
Component.onStatusChanged
andComponent.Ready
status)Notice for Performance: Signal and Javascript codes have some performance impact. It may be more performant to use bindings. Use Profiler to check that. If you want to set initial values of multiple property or you have already used
onCompleted
signal, so this will improve the performance!In fact, you just shouldn't. Binding is the base behaviour of QML, if you try to avoid it, then that's because you're not thinking the good way.
For exemple, if property two initial value is calculated with property one initial value but not property one value,
Then that mean you want to bind on Initial value not value, you should create a readonly property which value will be property one initial value :
It could seem a little heavy, but if you think about it, the initial value is what you wanna use, and so, the concept of the property is what you really want
Explicitly break the binding upon component completion:
The
two = two
assignment breaks the binding andtwo
is no longer updated asone
changes.