I'm trying to navigate the Qt MVC framework and currently have my code working fine with QStandardItemModel containing rows representing items and columns representing fields of the item.
However the underlying data for what goes in the QStandardItemModel is a list of objects, and having to convert that list of objects into rows and columns seems unnecessary.
Ideally I could just store my objects in the QStandardItemModel and not have to worry about columns. I see from QAbstractTableModel retrieve custom object on data changed that this is possible using Q_DECLARE_METATYPE and implementing QStyledItemDelegate.
However, I don't see how this could function with QDataWidgetMapper, which is something I also use. Is there a way to make this work, or am I going about it altogether incorrectly?
Let's say I have a class (note this is all pseudo code):
class Fruit {
string name;
string color;
bool goodForYou;
}
And say the real "data" is:
QList<Fruit> fruit;
fruit.append({"Orange", "orange", true});
fruit.append({"Apple", "red", true});
fruit.append({"Poison apple", "black", false});
Right now I'm defining an enum for the columns:
enum FruitColumns {
Name = 0,
Color = 1,
GoodForYou = 2
}
To populate the model:
StandardItemModel model;
for (i = 0; i < fruit.length; i++) {
Fruit f = fruit[i];
QStandardItem *item = new QStandardItem();
QModelIndex nameIndex = model.index(i, FruitColumns::Name);
QModelIndex colorIndex = model.index(i, FruitColumns::Color);
QModelIndex goodForYouIndex = model.index(i, FruitColumns::GoodForYou);
model.setData(nameIndex, f.name);
model.setData(colorIndex, f.color);
model.setData(goodForYouIndex, f.goodForYou);
}
Now I can get data to show up in a ListView:
QListView fruitListView;
fruitListView.setModel(&model);
When someone selects a fruit from the list, I have another widget that uses QDataWidgetMapper to map each field of the fruit to a textbox for the user to edit.
QDataWidgetMapper mapper();
mapper.setModel(model);
...
QLineEdit nameEdit();
QLineEdit colorEdit();
QCheckbox goodForYouEdit();
mapper.addMapping(nameEdit, FruitColumns::Name)
mapper.addMapping(colorEdit, FruitColumns::Color)
mapper.addMapping(goodForYouEdit, FruitColumns::GoodForYou)
...
mapper.setCurrentModelIndex(index);
Again, all working well. But how would this mapping work if I was only storing one "column" of data, where that data was my class (registered as a QVariant)?