Reputation: 2375
I am just starting to learn QML and I am kinda lost at what should I do when I want to read ListModel from settings.
My dilemma is:
1) If I define the model in C++ code I have no problems loading it (I have done similar stuff loads of times) but I am sacrificing my time to actually write (and later update) model code and then recompile each time I need to do it.
2) My other idea is to read settings file into QList of QVariantMap and create the model in QML file reading this list using javascript. This way I will only need 2 C++ functions, one to read the file section by section and one to write it. But as I said - I am only starting QML programming and not sure if it is sane or discouraged.
Can someone comment on good practices when one needs dynamic QML ListModel?
UPD: I seem to need to clarify the question:
Do I even need C++ data model if the stuff is simple enough to read from settings and then parse directly into ListModel via Javascript? Or are there pitfalls I am not aware of that make C++ way the only reasonable choice?
UPD2 After some mroe researching I am tempted to go with LocalStorage and forgo c++ altogether
Upvotes: 3
Views: 1587
Reputation: 11408
Making an existing C++ model editable is quit easy, since you get everything from Qt.
You have the following in .h
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
enum MyRoles {
SomeRole = Qt::UserRole,
// ...
}
// ...
bool setData(const QModelIndex &index, const QVariant &value, int role);
in .cpp
bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
switch (role) {
case SomeRole:
// your writer code
emit dataChanged(index, index, (QVector<int>(0) << SomeRole));
return true;
case SomeOtherRole:
// ...
return true;
default:
qCritical() << "MyModel.setData: Unknown role:" << role;
return false;
}
}
Now your can use QML internals to perfrom a write.
MyModelDelegate {
Button {
text: somerole
onClicked: {
// this will call setData with the correct row index and SomeRole
somerole = "some other value"
}
}
}
This C++ code is only recompiled when you add new roles, which should not happen very often or your write method changed.
Upvotes: 1