How can I avoid creating property bindings during initialization in QML?

I want to create a custom QML component with two properties, one and two , that should have default values ​​if they are left uninitialized. In particular, if two should get an initial value based on one . Following code

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

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

+7
qt qml
source share
3 answers

In fact, you simply shouldn't. Binding is the basic behavior of QML, if you try to avoid it, it is because you are not thinking of a good way.

For example, if the property two initial values ​​is calculated using the property one initial value , but not the property one value ,

Then this means that you want to bind the Initial value to not the value , you must create the readonly property , the value of which will be the property one initial value :

 readonly property int initialOne : 1; property int one : initialOne; property int two : 2 * initialOne; 

It may seem a little heavy, but if you think about it, the initial value is what you want to use, and therefore the concept of a property is what you really want

0
source share

Double check that there is no need to bind and be careful not to contaminate the codes.
You can quickly populate a property with a value as follows:

 window { id: win width: 300; height: 450 color: "#d8d8d8" Item { property int val1 property int val2 property int val3: parent.width //<-- Binding Component.onCompleted: { val1 = win.width; //<---| val2 = win.height; //<---|=== There is no binding. Just changes value /* ... */ } } } 

(I'm not sure you can set the initial value using Component.onStatusChanged and Component.Ready status)

Performance Notification: Signal Codes and Javascript have some performance impact. It may be more efficient to use bindings. Use Profiler to verify this. If you want to set the initial values ​​of the multiple property or you have already used the onCompleted signal, this will improve performance!

0
source share

Explicitly break the binding when the component completes:

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

The purpose of two = two breaks the binding, and two no longer updated as one changes.

0
source share

All Articles