Search code examples
c++qtqt5qtreeviewqtgui

QModelIndex::data not working


I have a QTreeView in my application with a data model. I'm capturing when items are double clicked with the following slot:

void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
    if (index.parent().isValid()) {
        QSharedPointer<GMResource> resource;

       resource = index.data(Qt::UserRole).value<QSharedPointer<GMResource> >();
        Workspace::GetSingleton()->OpenResourceEditor(resource);
    }
}

I expected the QModelIndex::data() method to (execute and) return the underlying QStandardItem::data() for the item referenced by that index, however its not returning anything. I set a breakpoint in my QStandardItem::data() method, and it's not even being called, so I might have incorrectly assumed what QModelIndex::data() actually returns.

How can I access the item data referenced by the QModelIndex (eg. Access to the original QStandardItem I added to the model).

Here is my data() method for my QStandardItem derived class:

virtual QVariant data( int role) const {
     if (role==Qt::UserRole) {
            return QVariant(resource);
     }
        return QStandardItem::data(role);
}

Any help would be much appreciated


Solution

  • I found the solution to the problem.

    I replaced this code:

    return QVariant(resource);
    

    With this code:

     QVariant r;
     r.setValue<QSharedPointer<GMResource> >(resource);
     return r;
    

    Seems to be working as expected. I guess the data() method was being executed, but the breakpoints weren't being triggered for some reason.