[Development] How to skip write property in qml's property binding?

JiDe Zhang zccrs at live.com
Fri Jul 19 11:25:01 CEST 2024


Thank you, but I can't use `text: fooObject?.foo ?? ""`, because I would not the `text` property change if when fooObject change to null.
If fooObject's new value is null, I want the text​ property keep old value.​​
________________________________
From: Pierre-Yves Siret <py.siret at gmail.com>
Sent: Friday, July 19, 2024 17:09
To: Fabian Kosmale <fabian.kosmale at qt.io>
Cc: JiDe Zhang <zccrs at live.com>; Qt邮件列表 <development at qt-project.org>
Subject: Re: [Development] How to skip write property in qml's property binding?

as always, it depends. If  you really want to set a binding based on a condition, but otherwise leave the value as it is, you want to use

Text {
     Binding on text {  value: fooObject.title; when: fooObject }
}

Note that the `when` only affects when the binding is applied to the target property, not when the value property is evaluated.
The above code will result in "Cannot read property 'title' of null" when fooObject is null, cf. https://bugreports.qt.io/browse/QTBUG-22005

Maybe work could resume on attempting to find a solution on this issue?

Meanwhile I think the best solution is `text: fooObject?.foo ?? ""`
This does assign an empty string but I think it does make sense and it is clearer in this case.
For custom and complex properties you could use `undefined` instead and potentially have a `RESET` function for a c++ defined `Q_PROPERTY`.

For more advanced use cases where you don't want to reset the value, use Binding and restoreMode.

Cheers,
Pierre-Yves Siret
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20240719/e301fd6f/attachment.htm>


More information about the Development mailing list