简体   繁体   English

QModelIndex ::数据不起作用

[英]QModelIndex::data not working

I have a QTreeView in my application with a data model. 我的应用程序中有一个带有数据模型的QTreeView。 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. 我希望QModelIndex::data()方法能够(执行并)返回该索引所引用项目的基础QStandardItem::data() ,但是它不会返回任何内容。 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. 我在QStandardItem::data()方法中设置了一个断点,甚至没有调用它,因此我可能错误地假设了QModelIndex::data()实际返回的内容。

How can I access the item data referenced by the QModelIndex (eg. Access to the original QStandardItem I added to the model). 如何访问QModelIndex引用的项目数据(例如,访问添加到模型的原始QStandardItem )。

Here is my data() method for my QStandardItem derived class: 这是我的QStandardItem派生类的data()方法:

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. 我猜想data()方法正在执行,但是由于某种原因并未触发断点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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