方案一:
通过QAbstractItemModel::canFetchMore与QAbstractItemModel::fetchMore两个接口实现。这两个接口会在某些情况下自动调用(初始化,滑动)。当滑动块滑动到底部且canFetchMore返回为true时
fetchMore会自动触发,通知ListView需要加载更多数据。例:
model.h
class ListModel : public QStandardItemModel {
Q_OBJECT
public:
explicit ListModel(QObject* parent = 0);
~ListModel();
//model中重写canFetchMore与fetchMore
bool canFetchMore(const QModelIndex& parent) const override;
void fetchMore(const QModelIndex& parent) override;
signals:
void addMore(int num); //发送信号给listView通知加载更多数据
public slots:
private:
int item_sum_;
int item_count_;
};
model.cpp
bool ListModel::canFetchMore(const QModelIndex&) const { //判断是否可加载更多
if (item_count_ < item_sum_)
return true;
else
return false;
}
void ListModel::fetchMore(const QModelIndex& parent) {
if (parent.isValid())
return;
int remainder = item_sum_ - item_count_; //剩余可加载资源
int add_item_num = qMin(10, remainder);
if (add_item_num<0)
return;
beginInsertRows(QModelIndex(), item_count_, item_count_ + add_item_num - 1);
item_count_ += add_item_num;
endInsertRows();
emit addMore(add_item_num); //通知l