Reputation: 21
I'd like to store custom objects (let's say instances of MyDataClass) in a tree structure, and linked with a view. So I used QStandardItemModel. I think that MyDataClass should inherit from QStandardItem :
class MyDataClass : public QStandardItem
{
public:
MyDataClass(QString name)
private:
vector<float> someData;
}
But I cannot figure out how to store instances of this class in a QStandardItemModel
.
I tried QStandardItem.setChild
and then appendRow
but it does not work and I think I don't really get the QStandardItemModel thing.
I think that the solution deals woth QStandardItem.setData
but I cannot figure out how it works for custom objects.
Upvotes: 0
Views: 2296
Reputation: 21
I have finally make it work using QVariant
.
To fill the model with custom data :
MyDataClass *data;
... // adding some data
QVariant variant;
variant.setValue(data);
QStandardItemModel model; // here is your model
QStandardItem *parentItem = model.invisibleRootItem();
QStandardItem *item = new QStandardItem();
item->setData(variant);
parentItem->setChild(0, 0, item); // adding the item to the root
Later, when you want to retrieve your data :
MyDataClass *retrievedData = model.invisibleRootItem()->
child(0, 0)->data().value<MyDataClass*>();
Note that I had to add a line in the class declaration :
class MyDataClass : public QStandardItem
{
public:
MyDataClass(QString name)
private:
vector<float> someData;
}
Q_DECLARE_METATYPE(MyDataClass *) // add this line
Thank you for your help.
Upvotes: 2
Reputation: 4344
You can use QStandardItemModel::setItemPrototype
.
http://qt-project.org/doc/qt-4.8/qstandarditemmodel.html#setItemPrototype
clone
.setItemPrototype
.Upvotes: 1