use*_*453 5 qt qabstractitemmodel
我有一个map = std::map<std::string, myItemModel *>
, 在那里myItemModel
继承QAbstractItemModel
.
我现在想将所有内容合并myItemModel
为一个myItemModel
(每个其他项目模型也可以)。这样就有了一个大myItemModel
。
有没有'qt-way'来做到这一点?
这是可以做到的,但这并不是一件小事。这取决于你的实现QAbstractItemModel
,这就是为什么它没有在 Qt 中完成。
以下是实现模型集合的步骤:
QAbstractItemModel
rowCount
并提供所有模型行的总和。 columnCount
并提供许多列。 index
,返回createIndex(row,column,NULL);parent
,返回QModelIndex(); 我希望你的模型不是树 data
,setData
解决对正确模型的调用。使用 #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)