문제

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

도움이 되었습니까?

해결책

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.

다른 팁

You should add Q_DECLARE_METATYPE(QSharedPointer<GMResource>) to be abe to wrap QSharedPointer<GMResource> type in QVariant

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top