QTreeView 普通数组的模型

QTreeView Model of a plain array

本文关键字:模型 数组 QTreeView      更新时间:2023-10-16

我有一个非常大的带有数字的普通数据数组。我想使用QTreeView和模型/视图方法来显示具有特定参数的树节点中分组的数据,例如数据值 <10、数据值 <100、数据值<1000。

官方树模型示例展示了如何对项目节点使用分层数据结构,这对我来说是不好的选择。

我尝试从QAbstractItemModel自己编写模型,但我什至无法意识到如何为组节点(例如<10、<100、<1000)及其子节点编写parent()方法。

是否可以编写这样的模型?

您需要创建"人工"父项,它们是没有值但只对应于数据值<100 的项目的父项的模型索引。

数据值<100 的每个项目将引用相同的父项。当被要求提供孩子时,这位父母将需要提供所有这些项目(以及应用rowCount()的孩子数量)。

bool MyModel::isCategory(const QModelIndex &index) const
{
    /* Based on your internal tracking of indexes, return if this is 
       a category (with children), false if not */
}
int MyModel::rowCount(const QModelIndex & parent) const
{
    if (!parent.isValid()) {
        /* This is top level */
        /* Return the number of different categories at top level */
    }
    if (isCategory(parent)) {
        /* This is a parent category (for example items with data value < 100 */
        /* Return the number of indexes under it */
    }
    /* This is a child element with just data in it, no children */
    return 0;
}
QModelIndex MyModel::index(int row, int column, const QModelIndex & parent) const
{
    if (!parent.isValid()) {
        /* Return QModelIndex corresponding to the nth global category, with n = row */
    }
    /* return the nth sub-element of the category represented by parent, with n = row */
}
QModelIndex QAbstractItemModel::parent(const QModelIndex & index) const
{
    /* If index is a top level category, return an empty QModelIndex */
    /* Otherwise return the QModelIndex corresponding to the bigger category */
}

在简化的情况下提供最小的代码示例,如果代码仍然不够,则代码不起作用。