We have defined a Qt property warningLevel
in the C++ class MainModel
:
Q_PROPERTY(WarningLevel::Enum warningLevel READ warningLevel
WRITE setWarningLevel NOTIFY warningLevelChanged)
We want to use this property in QML. For example, we want to colour a rectangle according to the warningLevel
:
import com.embeddeduse.models 1.0
// ...
property MainModel mainModel : MainModel {}
Rectangle {
color: toColor(mainModel.warningLevel)
// ...
}
function toColor(level) {
switch (level) {
case WarningLevel.Error:
return "red"
case WarningLevel.Warning:
return "orange"
case WarningLevel.Info:
return "green"
case WarningLevel.Debug:
return "purple"
default:
return "magenta"
}
}
Note how we access the C++ property mainModel.warningLevel
from QML to set the color
of the rectangle and how we use symbolic enum constants like WarningLevel.Info
in the function toColor()
.
It is similarly easy to use a list of the symbolic enum constants as the model of a Repeater
and to assign the warning level by the user to the property mainModel.warningLevel
in the onReleased
handler of a MouseArea
.
Repeater {
model: [WarningLevel.Error, WarningLevel.Warning, WarningLevel.Info,
WarningLevel.Debug]
Rectangle {
color: toColor(modelData)
// ...
MouseArea {
anchors.fill: parent
onReleased: mainModel.warningLevel = modelData
}
}
}
I’ll show you in the rest of this post how to write your C++ code so that you can use a C++ property of enum type easily in QML.
Read More »Passing Enum Properties between C++ and QML