View Full Version : How to access the class object on click of QTreeView Item

31st August 2018, 09:51

Consider the following two structures, where "Contact" is the main structure which has list of "Address" objects as one among its data member.

struct Address
QString pincode;
QList<QString> telephone;

struct Contact
QString firstName;
QString secondName;
QString address;
QList<Address*> addressList;

I created a QTreeView which inherits from QAbstractItemModel. Each QTreeViewItem parent should be mapped to "Contact" data members where the "addressList" should be mapped as a child item for that particular parent. I am trying to write a user defined function logic to parse the structure members and add as a Parent/child accordingly.

My use case is that , when i click the child row (addressList), i need to retreive the entire Address object but not the Contact object. How can i achieve this using ModelIndex?


1st September 2018, 18:05
Hi, Can anyone help me on this

14th September 2018, 08:32
Hi, you can store any data you like (e.g. pointers to your structs) using QAbstractItemModel::setData() using Qt::UserRole or higher values for the "role" parameter.


14th September 2018, 18:32
And you can return this pointer to the outside world when you implement QAbstractItemModel::createIndex() for your tree model. The third, optional argument to this method is a void * pointer. Your program can retrieve that pointer from the QModelIndex instance using the QModelIndex::internalPointer() method.