在视图中存储有关项目的持久信息 [英] Storing persistent information about items in view

查看:48
本文介绍了在视图中存储有关项目的持久信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有直接基于 QAbstractItemView 的我自己的视图.一般来说,我需要存储有关特定模型项目的一些信息.

I've my own view based directly on QAbstractItemView. Generally speaking I need to store some information about particular model's item.

所以在我看来,我有一个从 QModelIndex 到描述特定项目的结构的映射.然后我主要在视图的 paintEvent 上使用这些数据.

So in my view I have a map from QModelIndex to struct describing partical item. Then I use those data mostly on view's paintEvent.

问题是,QModelIndex 不是持久化的,它可能会过时.因此,当从模型中插入或删除行时,某些 QModelIndex 可能会变得无效,我不应该继续使用它们.

The problem is, that QModelIndex is not persistent, it may get outdated. So when rows are inserted or removed from model, some QModelIndex may become invalid and I should not relay on them.

那么如何在模型中的项目和我在视图中使用的一些装饰数据之间建立关系?

How then can I build relation between item in model and some decoration data I use in view?

QPersistentModelIndex 似乎是处理此类事情的合适工具,但我知道它的性能(我的模型和视图可能很大).

QPersistentModelIndex seems to be proper tool for such things, however I'm aware of its performance (my model and view may be huge).

QPersistentModelIndex 的另一个问题是它可能不应该用作地图的键(就像我的情况一样),因为它可能(并且将会)改变并使地图不一致.

Another problem with QPersistentModelIndex is that it probably should not be used as map's key (as it is in my case) as it may (and will) change and make map inconsistent.

我查看了 Qt 对 QTreeView 和 QListView 的实现,以了解它们如何处理行删除/插入,但它们似乎只是删除了所有数据.

I've took a look at Qt's implementation of QTreeView and QListView to see how they deal rows removal/insertion, but it seems they simply drop all the data.

所以在这一点上,我看不到任何简单的方法来解决我的问题.

So at this point I cannot see any easy way to solve my problem.

推荐答案

您可以安全地使用 QPersistentModelIndex 作为映射或哈希键.即使底层 QModelIndex 发生变化,持久性"部分也确保所有 QPersistentModelIndex 保持最新,同时保留其身份,即 operator ==qHash() 返回一致的值.

You can safely use a QPersistentModelIndex as a map or hash key. Even if the underlying QModelIndex changes, the "persistent" part ensure that all the QPersistentModelIndex are kept up to date while preserving their identities, i.e operator == and qHash() return consistent values.

话虽如此,您不应在视图中存储有关索引的数据.数据应该由模型存储.这似乎是它在 Qt 类中的完成方式:视图对 QAbstractItemModel::data() 进行了大量调用.

That being said, you should not store data about the index in your view. The data are supposed to be stored by the model. And this seems to be how its done in Qt classes: views are making a lot of calls to QAbstractItemModel::data().

我认为值得存储在视图中的唯一数据是缓存数据",即以下值:

The only data that I would deem worthy to be stored in the view is "cache data", i.e values that are:

  • 模型不直接提供
  • 需要从模型数据中进行大量计算
  • 特定于视图

如果不满足这 3 个条件中的任何一个,我个人的偏好是将数据存储在模型中.

If any of these 3 conditions is not met, my personal preference would be to store the data in the model.

这篇关于在视图中存储有关项目的持久信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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