我创建了一个名为 PresetTableModel
的 QAbstractTableModel
,并将其连接到 QTableView
。我实现了 rowCount、columnCount 和数据函数。如果我让 rowCount
返回固定数字,则一切正常,但一旦我让它返回变量值, ListView 就不会显示任何行。下面代码中的调试语句显示的大小值从 0 开始,但在列表填充后更改为 9。
int PresetTableModel::rowCount(const QModelIndex & /*parent*/) const
{
qDebug() << preset_list.count();
return preset_list.size();
}
我还需要做些什么来强制它更新行数吗?
最佳答案
修改底层数据时,必须使用模型的通知机制来通知 View 。例如,附加数据时:
beginInsertRows(QModelIndex(), preset_list.size(), preset_list.size()+1); //notify that two rows will be appended (rows size() and size() + 1)
preset_list.append(something);
preset_list.append(somethingelse);
endInsertRows(); //notify views that you're done with modifying the underlying data
因此,在删除行时必须调用 beginRemoveRows() 和 endRemoveRows(),并在更新现有条目时发出 dataChanged()。
附带说明,您的 rowCount() 方法应为
if (!parent.isValid())
return preset_list.size(); //top-level: return list size
else
return 0; //list item: no further children (flat list)
限制深度。否则列表中的每个项目都会再次具有preset_list.size()条目。
关于qt - 为什么 QTableView 行数不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8595981/