Proper way to binding QML Controls and C++ model
-
Hi. I wonder what is the best way binding QML control type and C++ model.
// My C++ model class Backend : public QObject { Q_OBJECT Q_PROPERTY(bool myCheck READ myCheck WRITE SetMyCheck NOTIFY myCheckChanged) // ... }
// QML binding CheckBox { id: qmlCheckBox checked: backend.myCheck onCheckedChanged: backend.myCheck = checked }
Like above, when C++ model(@myCheck) is changed in C++ code, then it should be notified to QML so that @qmlCheckBox is also changed.
Changing in QML also should change C++ model. (vice versa)
But there was a binding loop detected warnings.
I KNOW WHY THERE IS BINDING LOOP. I wonder how to do what I want without binding loop.
Thanks. -
@fromis_9 Controls usually provide a signal to indicate that a change has come from a user interaction signal, you should use this one instead of the "raw"
<property>Changed
signal that will fire both on backend and frontend changes.For CheckBox it is the
toggled
signal, for ComboBoxactivated
, for TextFieldtextEdited
, ...So in your case it would be:
CheckBox { id: qmlCheckBox checked: backend.myCheck onToggled: backend.myCheck = checked }
Make sure to also not emit the notify signal in the setter if the property doesn't actually changed, generally done with an if at the start:
void Backend::SetMyCheck(bool myCheck) { if (myCheck == m_myCheck) return; m_myCheck = myCheck; emit myCheckChanged(); }
-