Tutorial :Qt getting reference of custom data type of QStandardItemModel to change it


It's getting a little weird I can't see a method to actually change the "data" of a QStandardItemModel. For example:

struct TestStruct {      std::vector<int> testVector;      void addNumber(int i){            //this method will modify the member vector      }  };  Q_DECLARE_METATYPE(TestStruct)    QStandardItemModel* model = QStandardItemModel(1,1);  QModelIndex index = model->index(0,0);  TestStruct test;  test.addNumber(1);  model->setData(index, qVariantFromValue(test));  

With that, I will effectively have added a std::vector with the number 1 to the index {0,0} of the model. But how would I add another number to that TestStruct's vector from places that don't have access to the TestStruct instance anymore?

The "data" function returns a QVariant that can be casted as a TestStruct but it's a copy and I need a reference... get it?


Yes it will return the value only and not it's reference.

A workaround for this is, you can get the struct by Typecasting the QVariant. Then modify your testVector.

After modifications, call again

model->setData(index, qVariantFromValue(newTest));  

where newTest is your struct with the modified Vector.

Hope it helps.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »