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

Fabian Kosmale fabian.kosmale at qt.io
Fri Jul 19 08:37:45 CEST 2024


Hi,

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 }
}
Compare https://doc.qt.io/qt-6/qml-qtqml-binding.html#conditional-bindings. Set restoreMode depending on your needs.

If you don't need an actual binding, but only the value, then you can use

Text {
     id: mytext
     Component.onCompleted: {  if (fooObject) mytext.text = fooObject.name }
}
if the nullishness of fooObject never changes. If it can change, you need to react to it with a Connection element,  a connection, or a property change handler
(depending on where the object is defined/how it is exposed to QML) or you again fall back to Binding.

An alternative would be to take a step back, and  to consider why you don't want to have the write to begin with. If you want to preserve a default value, you
might want to consider exposing that one, too, so that you can write:

// MyText.qml
Text { property string defaultText: "some value"; text: defaultTtext }

// Usage.qml
MyText { id: myText; text: fooObject?.title ?? myText.defaultText }

This of course assumes that you have control over the item setting the default value.

Kind regards,
Fabian Kosmale

________________________________________
Von: Development <development-bounces at qt-project.org> im Auftrag von JiDe Zhang <zccrs at live.com>
Gesendet: Freitag, 19. Juli 2024 07:31
An: Qt邮件列表
Betreff: [Development] How to skip write property in qml's property binding?

For an example:

Text {
    text: fooObject?.title
}

When the fooObject is null, will got a qml error "Unable to assign [undefined] to QString".

I don't want the error, so, how to skip write value for "text" property when fooObject is null?

Text {
    text: fooObject?.title ?? text
}

This is a workaround, but it is a magic, maybe will got a cycle binding?

Text {
    text: fooObject?.title ?? bypass
    objectName: {
       if (fooObject)
            return fooObject.name
       bypass
    }
}

This syntax will more easily understand.


More information about the Development mailing list