结合 QAbstractItemModels

use*_*453 5 qt qabstractitemmodel

我有一个map = std::map<std::string, myItemModel *>, 在那里myItemModel继承QAbstractItemModel.

我现在想将所有内容合并myItemModel为一个myItemModel(每个其他项目模型也可以)。这样就有了一个大myItemModel

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

Eze*_*zee 4

这是可以做到的,但这并不是一件小事。这取决于你的实现QAbstractItemModel,这就是为什么它没有在 Qt 中完成。

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

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

ps 考虑创建索引映射的缓存。

这是将基本模型索引转换为子模型索引的方法示例:

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();
Run Code Online (Sandbox Code Playgroud)

}

这是将子模型索引转换为基本模型索引的方法示例:

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();
}
Run Code Online (Sandbox Code Playgroud)