Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the index for a given item in a QTreeView / Model application

Tags:

qt

My Qt desktop app was built on the editabletreemodel sample application. In the sample application in treemodel.cpp there is a mthod called getItem() which takes a QModelIndex as a parameter and returns a pointer to a TreeItem.

This is what the method looks like:

TreeItem *TreeModel::getItem(const QModelIndex &index) const
{
    if (index.isValid()) {
        TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
        if (item)
            return item;
    }
    return rootItem;
}

I would like to do the reverse - that is return a QModelIndex for a given TreeItem.

How can I do this?

like image 986
Michael Vincent Avatar asked Apr 28 '15 13:04

Michael Vincent


1 Answers

Difficult... very difficult. And directly not possible. And if you use the TreeItem as in the Qt example code you are out of luck. What you can do is:

  1. Add a unique identifier to your TreeItem
  2. Modify your data function to get this unique id for a user defined role. You are the user who has to define this new role ;-)
  3. Use **QModelIndexList QAbstractItemModel::match(...) to find the index for the TreeItem, which returns the unique id for your user role.
like image 158
Greenflow Avatar answered Sep 20 '22 11:09

Greenflow