gpt4 book ai didi

qt - 结合 QAbstractItemModels

转载 作者:行者123 更新时间:2023-12-03 22:47:38 29 4
gpt4 key购买 nike

我有一个 map = std::map<std::string, myItemModel *> ,其中 myItemModel继承QAbstractItemModel .

我现在要合并所有 myItemModel合一myItemModel (其他所有元素模型也可以)。
这样就有了一大 myItemModel .

有没有'qt-way'来做到这一点?

最佳答案

这是可以做到的,但这不是微不足道的。这取决于您对 QAbstractItemModel 的实现这就是为什么它没有在 Qt 中完成的原因。

以下是实现模型集合的步骤:

  • 创建一个继承自 QAbstractItemModel 的新类
  • 添加将其他模型添加到该模型的方法
  • 处理来自包含索引的子模型的所有信号(您需要更改它们,查看 #10)
  • 转发所有不包含索引的信号。
  • 实现 rowCount并提供所有模型行的总和。
  • 实现 columnCount并在您的模型中提供许多列。
  • 实现 index , return createIndex(row, column, NULL);
  • 实现 parent , 返回 QModelIndex();希望你的模型不是树
  • 实现 data , setData等解决对正确模型的调用。使用 #10 中的方法转换索引。
  • 创建将子模型索引转换为基本模型索引并返回的方法。
  •      Example (indexes):       BaseModel ChildModel1 ChildModel2        0,0       0,0                 1,0       1,0                 2,0                   0,0        3,0                   1,0        4,0                   2,0

    p.s. Think about creating a cache of indexes mapping.

    This is an example of a method to convert a base model index to a child model index:

    const QModelIndex childModelIndex(const QModelIndex& baseModelIndex) const
    {
    if (!baseModelIndex.isValid())
    {
    return QModelIndex();
    }

    int count = 0;
    const int row = baseModelIndex.row();

    for (QList<QAbstractTableModel*>::const_iterator it = m_models.begin();
    it != m_models.end(); it++)
    {
    const int currentCount = (*it)->rowCount();

    if (row >= count && row < count + currentCount)
    {
    return (*it)->index(row - count, 0);
    }

    count += currentCount;
    }

    ASSERT(false);

    return QModelIndex();

    }

    这是转换 的方法示例子模型索引到基本模型索引 :
    QModelIndex baseModelIndex(const QModelIndex& childModelIndex) const
    {
    int row = childModelIndex.row();

    for (QList<QAbstractTableModel*>::const_iterator it = m_models.begin();
    it != m_models.end(); it++)
    {
    if (childModelIndex.model() == *it)
    {
    return index(row, ind.column());
    }

    row += (*it)->rowCount();
    }

    return QModelIndex();
    }

    关于qt - 结合 QAbstractItemModels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661544/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com