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

Pierre-Yves Siret py.siret at gmail.com
Fri Aug 9 08:55:52 CEST 2024


Le ven. 9 août 2024 à 01:56, Mike Trahearn <
miketrahearn at imagineuisoftware.com> a écrit :

> To Ulf’s point,
>
> You would indeed not be able to restore a previous value using text:
> fooObject?.title ?? text because it will have been overwritten whenever
> fooObject?.title yields a valid value.
> The most reasonable solution therefore is to use the Binding element which
> is designed to restore the previous/original binding or value of the
> binding target property whenever its “when” property is false.
> It isn’t the most concise but it is bomb-proof and explicit, and is fully
> aligned to your requirements.
>

OP doesn't want to restore the previous value, but keep the last "valid"
value. The behavior of `text: fooObject?.title ?? text` is fine for them.
The question is about making it a bit less hacky since that line doesn't
look trustworthy.

    Binding {
>         yourTextObject.text: fooObject.title // assuming title will be
> valid if fooObject !== null, if not the “when” property might need
> fooObject?.title
>         when: fooObject  // else it will be restored to being bound to
> the “defaultString" value
>     }
> }
>

While the above lacks the `restoreMode: Binding.RestoreNone` already
mentioned by Fabian, it will also trigger some warnings when fooObject is
null. The `fooObject.title` expression, although not applied, will be
evaluated even though `when` is false so this needs to be checked for.
`fooObject?.title ?? ""`

So the correct solution would be
            Binding {
                textObject.text: fooObject?.title ?? ""
                when: fooObject
                restoreMode: Binding.RestoreNone
            }
or
            Binding on text {
                value: fooObject?.title ?? ""
                when: fooObject
                restoreMode: Binding.RestoreNone
            }

If we want to follow the route suggested by Giuseppe, we could write a new
"NoUndefinedBinding" type like the following:

import QtQml

Binding {
    property var val // we need a new property because value has no NOTIFY
signal :(
    when: typeof val !== "undefined"
    value: val
    restoreMode: Binding.RestoreNone
}

Usage:
Text {
    NoUndefinedBinding on text { val: fooObject?.title }
}

But is that really better than the initial `text: fooObject?.title ?? text`
??

Regards,
Pierre-Yves
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20240809/bb53f7b3/attachment.htm>


More information about the Development mailing list