FANGYEFENG

Apr 16, 2024

Qt model动态增添数据实现

在Qt中,使用model/view来实现数据的显示是非常灵活的一种做法,数据增添、删除、重置都可以很容易的实现。一直以来,我实现ListView的下拉动态增添数据项都是采用 contentY originY contentHeight这三个变量的数值计算这种做法。但最近在读官方示例Fetch More Example学习到了更为简单的方法。

QAbstractItemModel中有fetchMorecanFetchMore这两个虚函数,默认实现是空的。当model对应的view需要请求更多的数据时,便会先调用canFetchMore这个方法,比如下拉到底部了,如果返回值为真,便调用canFetchMore去获取更多的数据。因此我门可以自己重写实现这两个方法以达到动态加载数据的目的。

1
2
3
4
5
6
bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
if (parent.isValid())
return false;
return; // 判断是否还有剩余数据
}
1
2
3
4
5
6
7
8
9
10
void FileListModel::fetchMore(const QModelIndex &parent)
{
if (parent.isValid())
return;
beginInsertRows(QModelIndex(),index,index);
/*
添加数据的操作
*/
endInsertRows();
}
OLDER > < NEWER