qtqmlqproperty

How to remove QML binding on property from C++?


With QML a property value can be based on another object property's value, it is called binding and it will update your value everytime the property you depend on is updated.

Like in this example, the implicitWidth of CppItem is half of the parent's width and the Text will fill the layout. If you resize the window, the CppItem width is updated.

Window
{
    RowLayout {
        anchors.fill: parent

        CppItem {  implicitWidth: parent.width * 0.5  }
        Text    {  Layout.fillWidth: true  }
    }
}

In my problem CppItem is a QQuickItem with some C++ code, and in some specific cases the C++ code will set the implicitWidth with the following code.
I know I could use setImplicitWidth but I am not sure it would make a difference for my problem, and anyway you can not do that if the property is not declared in C++ but in a loaded QML file.

setProperty("implicitWidth", 100);

The property value is set but the QML binding is not removed. So the C++ code above is not equivalent to the QML code :

cppItem.implicitWidth = 100

With the C++ code, any change on parent.width will trigger an update on cppItem.implicitWidth and set again the value cppItem.implicitWidth.

How can I remove this binding from C++ ?


Solution

  • Using QObject::setProperty in C++ does not break the binding previously made in QML.

    But using QQmlProperty::write does break the binding.

    // setProperty("implicitWidth", 100); --> Does not break binding
    QQmlProperty::write(this, "implicitWidth", 100);