简体   繁体   中英

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

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.

您应该添加Q_DECLARE_METATYPE(QSharedPointer<GMResource>)以便将QSharedPointer<GMResource>类型包装在QVariant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM