简体   繁体   中英

Storing custom objects in QStandardItemModel

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.

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.

You can use QStandardItemModel::setItemPrototype .
http://qt-project.org/doc/qt-4.8/qstandarditemmodel.html#setItemPrototype

  1. Inherit from QStandardItem and reimplement method clone .
  2. Create a new instance of your item and pass it to setItemPrototype .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM