Attach custom object to QStandardItem in Qt

I use QTreeView to show some data to the user. I want to bind the actual object to each node represented using QStandardItem .

To save a reference to an object in QStandardItem :

 QStandardItem *child = new QStandardItem(s); child->setFlags(child->flags() & ~Qt::ItemIsEditable); child->setData(QVariant(QVariant::UserType, i), Qt::UserRole + 10); 

To access the actual object when it is clicked in the user interface:

 void MyOtherClass::handleTreeViewSelectionChanged(const QModelIndex &i) { MyClass* o = i.data(Qt::UserRole + 10).value<MyClass*>(); // do other stuff with o } 

The above call just returns NULL . Does anyone know how to handle this requirement?

I found absolutely nothing useful on the Internet.

Any help would be greatly appreciated.

+6
source share
1 answer

To save your element in QStandardItem, you need to make sure that you register your type with QMetaType. For example, you might have this definition:

 class MyType { public: MyType() : m_data(0) {} int someMethod() const { return m_data; } private: int m_data; }; Q_DECLARE_METATYPE(MyType*); // notice that I've declared this for a POINTER to your type 

Then you can save it in QVariant as follows:

 MyType *object = new MyType; QVariant variant; variant.setValue(object); 

Given a properly registered metatype for your type, you can now do something similar with QStandardItems:

 MyType *object = new MyType; QStandardItemModel model; QStandardItem *parentItem = model.invisibleRootItem(); QStandardItem *item = new QStandardItem; item->setData(QVariant::fromValue(myType)); // this defaults to Qt::UserRole + 1 parentItem->appendRow(item); 

And then remove it:

 void MyOtherClass::handleTreeViewSelectionChanged(const QModelIndex &i) { MyType* o = i.data(Qt::UserRole + 1).value<MyType*>(); // do other stuff with o } 
+5
source

All Articles