QListView 的高性能加载方案

本文介绍了两种QListView的高性能加载方案:一是利用QAbstractItemModel的canFetchMore和fetchMore接口自动触发加载更多数据,适用于滑动到底部时加载;二是借助QtConcurrent进行异步加载,将数据加载工作放到后台线程,确保UI流畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方案一:

通过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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值