QML / C++ best practice
Here are some hints what to do and not to do from my experience when creating QML applications with C++ backend, also see the “official” qt best practice page
Command Query Segregation :
Functions that change state should not return values and functions that return values should not change state.
see http://cqrs.nu/Faq/command-query-responsibility-segregation
Do:
- declare readonly attributes in C++ & bind to them in QML
- use Q_INVOKABLEs for actions which change state like this ctrl.actionWhichChangesX(42)
Dont:
- set C++ attributes from QML like this ctrl.x = 42
Signal names:
reflect events, something that has happened, so write in past tense
Do:
- signals:
void stageCleared(…)
Dont:
- signals:
void clearStage(…)
Binding model properties to interaction elements
If you want to bind a model property directly to a UI element which is used to edit this property, e.g. a line edit there’s a problem that the binding gets lost when editing has finished.
TextField {
text : myModel.myTextProperty
onEditingFinished : controller.setMyTextProperty(text)
}
There are several solutions for this, you can for example reestablish the binding after editing using Qt.binding like this:
onEditingFinished: {
controller.setMyTextProperty(text)
text = Qt.binding(function() { return myModel.myTextProperty }
}
or dont bind at all but work with an additional property like this :
TextField {
property string myText : myModel.myTextProperty
onMyTextChanged: text = myText onEditingFinished : controller.setMyTextProperty(text)
}
Debugging broken bindings
set QT_LOGGING_RULES=”qt.qml.binding.removal.info=true”