Apr 16, 2024
Qt model动态增添数据实现
在Qt中,使用model/view来实现数据的显示是非常灵活的一种做法,数据增添、删除、重置都可以很容易的实现。一直以来,我实现ListView的下拉动态增添数据项都是采用 contentY originY contentHeight这三个变量的数值计算这种做法。但最近在读官方示例Fetch More Example学习到了更为简单的方法。
QAbstractItemModel中有fetchMore和canFetchMore这两个虚函数,默认实现是空的。当model对应的view需要请求更多的数据时,便会先调用canFetchMore这个方法,比如下拉到底部了,如果返回值为真,便调用canFetchMore去获取更多的数据。因此我门可以自己重写实现这两个方法以达到动态加载数据的目的。
1 | bool FileListModel::canFetchMore(const QModelIndex &parent) const |
1 | void FileListModel::fetchMore(const QModelIndex &parent) |