Models should be part of the business logic and belong to C++.
Accessing model data is currently readonly. You must provide a Q_INVOKABLE setData method in your model if you want to modify data in a C++ model.
Q_INVOKABLE void setDataForRow(int row, const QVariant &data, const QString &role)
{
int role = roleNames().key(role); // this is slow ;-(
switch (role) {
// put data into model here, don't forget to emit dataChanged if data has actually changed
}
}
Instead of providing the role as a string you can also use Q_ENUMS to make your Roles visible to QML:
class MyModel : public QAbstractListModel {
// ...
Q_ENUMS(MyRole)
// ...
public:
enum MyRole {
FirstRole = Qt::UserRole + 1000,
SecondRole
}
}
Q_INVOKABLE void setDataForRow(int row, const QVariant &data, int role)
{
switch (role) {
// put data into model here
}
}
Delegate Example
ListView {
anchors.fill: parent
model: MyModel {}
delegate: Row {
TextInput {
text: model.firstRole
onTextChanged: model.setDataForRow(model.index, text, "firstRole" /* or MyModel.FirstRole */)
}
}
}
↧