2

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++ ?

ymoreau
  • 3,402
  • 1
  • 22
  • 60
  • 3
    `How can I remove this binding from C++ ?` if you did your app design right, you shouldn't have to. Touching any QML from C++ is considered bad practice, and things like property bindings are not even in the public C++ API, so that's even worse. – dtech Mar 29 '18 at 15:50
  • 1
    @dtech I agree that a better design would avoid this situation, but you don't always choose the design. And anyway the behaviour is not intuitive, so I think it is nice to point this out ! – ymoreau Mar 30 '18 at 09:18

1 Answers1

2

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);
ymoreau
  • 3,402
  • 1
  • 22
  • 60