从数据项创建QModelIndex [英] Create a QModelIndex from a Data Item

查看:318
本文介绍了从数据项创建QModelIndex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从模型中的特定数据创建QModelIndex的方法.我可以通过以下方式从QModelIndex转到数据项:

I'm looking for a way to create a QModelIndex from a particular piece of data in my model. I can go from a QModelIndex to a data item via:

CustomData *data = static_cast<CustomData *>(modelIndex.internalPointer());

但是我正在寻找一个反函数:

But I'm looking for an inverse function to go from:

QModelIndex *index = createIndex(data); // ??

我已经实现了数据之间的链接,非常类似于简单树模型示例( http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html ).我的视图正确显示了数据,但是有相当大的滞后.我想发出dataChanged(QModelIndex,QModelIndex)来立即查看视图更新,因为我认为延迟是由于等待视图更新所致.

I've implemented linkages between my data very similar to the simple tree model example (http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html). My view displays the data correctly, but with considerable lag. I'd like to emit dataChanged(QModelIndex, QModelIndex) to see updates to the view instantly, since I think the lag is due to waiting for the view to update.

在链接的示例中,我试图从TreeItem获取其在QTreeModel中的相应索引.

In the linked example, I'm trying to get from a TreeItem to its corresponding index in the QTreeModel.

推荐答案

视图不会定期更新.它会根据需要进行更新,从模型的角度来看,这意味着任何意义.如果当某项更改一个或多个数据角色值时您的模型不发出dataChanged,则您的模型就被破坏了.

The view doesn't update periodically. It updates as needed, and from the point of view of your model, that means anything. If your model doesn't emit dataChanged when an item changes one or more of its data role values, then your model is simply broken.

要解决此问题,您有两种方法:

To fix it, you have two approaches:

  1. 将行和列添加到CustomData.添加/删除行/列时,您必须保持这些更新.

  1. Add the row and column to CustomData. You'll have to keep these updated as you add/remove rows/columns.

在需要时,迭代项的父项中的项以找到子项-完成后,您将从迭代项的循环中获得行/列.

When needed, iterate the items in the parent of your item to find the child - when you do, you get the row/column from the loop that iterates the items.

我认为您一直在努力.您很可能根本不需要实现CustomData-只需使用QStandardItem并将数据存储在变量中即可.然后,QStandardItemModel为您处理迭代器和信号的所有详细信息.要将自定义数据类型存储在QStandardItem用于存储的QVariant中,只需通过Q_DECLARE_METATYPE(YourType)将其公开给QVariant机器即可.

I think that you're trying too hard, through. You most likely do not need to implement CustomData at all - but merely use QStandardItem and store the data in the variant. Then, QStandardItemModel handles all the details of iterators and signals for you. To store a custom data type in the QVariant that the QStandardItem uses for storage, simply expose it to the QVariant machinery via Q_DECLARE_METATYPE(YourType).

您需要提供一个令人信服的论点,即QStandardItem在某种程度上不足以满足您的需求.

You'd need to provide a convincing argument that somehow a QStandardItem is insufficient for your needs.

这篇关于从数据项创建QModelIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆