今天在完成如下折叠功能时,
双击常规可以正常折叠,但是点击自编程时,程序报错。
ASSERT: "last < rowCount(parent)" in file itemmodels\qabstractitemmodel.cpp, line 2782
折叠时用到的是以下方法。
[protected] void QAbstractItemModel::beginRemoveRows(const QModelIndex &parent, int first, int last)
//我的代码
beginRemoveRows(QModelIndex(), index.row() + 1, index.row() + node->children.size());
endRemoveRows();
可以看出是因为 last 没有小于总行数(rowCount)。这就有疑问了为什么点击常规可以正常折叠不报错。反而点击自编程每次都报错,按道理有问题应该同时报错。
找到原因,如下,
//重载modelrowCount
int NavModel::rowCount(const QModelIndex &parent) const
{
return listNode.size();
}
//折叠部分代码
/refreshList();//刷新不应该放在删除行之前这样可能导致rowCount返回数据错误。
if (!node->collapse) {
beginInsertRows(QModelIndex(), index.row() + 1, index.row() + node->children.size());
endInsertRows();
} else {
beginRemoveRows(QModelIndex(), index.row() + 1, index.row() + node->children.size());
endRemoveRows();
}
refreshList();//应该放在删除行之后,这样比较好