A good way to allow editing of Model items?
-
hey i've been learning normal Qt for over 7 months and i only just started learning some Qml after hearing so much about it. I've been trying to get a better understanding of data models and views in both normal Qt and Qml. Following the standard Qml approach of using a Rectangle and Text element in the delegate, what is a good way to let a user edit the value of text in the delegate's Text element?
I was wondering is this where the normal Qt will come in? as in don't use qml's ListModel, but instead a model from Qt ? but then i realized the editing still needs to take place on the qml screen, so im still wondering how i can let a user edit the model's data item/role's value?
Also ive heard its better to subclass a Qt model if the application is too complex for Qml. Could anyone please give me an idea of such a situation?
-
I think it's convenient to operate ListModel (modify and so on) using Qml:
http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-listmodel.html -
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 */)
}
}
}
@ -
[quote author="njeisecke" date="1368618421"]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.
[/quote]
Thank's so much for your response and detailed reply neisecke.