QAbstractListModel配合QListView实现延迟加载的简单例子

运行效果

QAbstractListModel配合QListView实现延迟加载的简单例子_第1张图片

主要代码:

main.cpp

#include 
#include 
#include "listviewmodel.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    ListViewModel listViewModel;
    QListView listView;
    listView.setModel(&listViewModel);
    listView.resize(100, 100);
    listView.show();

    return a.exec();
}

ListViewModel.h

#ifndef LISTVIEWMODEL_H
#define LISTVIEWMODEL_H

#include 
#include 

class ListViewModel : public QAbstractListModel
{
    Q_OBJECT
public:
    explicit ListViewModel(QObject *parent = 0);
    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role) const;
    bool canFetchMore(const QModelIndex &parent) const;
    void fetchMore(const QModelIndex &parent);

private:
    QList m_dataList;

private slots:
    void loadMoreData();
};

#endif // LISTVIEWMODEL_H

ListViewModel.cpp

#include "listviewmodel.h"
#include 
#include 

ListViewModel::ListViewModel(QObject *parent)
    : QAbstractListModel(parent)
{
    QTime time=QTime::currentTime();
    for(int i=0; i<10; i++)
    {
        m_dataList.push_back(QString("%1 -- %2").arg(i).arg(time.toString("hh:mm:ss")));
    }
}

int ListViewModel::rowCount(const QModelIndex &parent) const
{
    return m_dataList.size();
}

int ListViewModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant ListViewModel::data(const QModelIndex &index, int role) const
{
    if(role==Qt::DisplayRole)
    {
        return m_dataList.at(index.row());
    }
    return QVariant();
}

bool ListViewModel::canFetchMore(const QModelIndex &parent) const
{
    return true;
}

void ListViewModel::fetchMore(const QModelIndex &parent)
{
    QTimer::singleShot(1000, this, SLOT(loadMoreData()));
}

void ListViewModel::loadMoreData()
{
    int currentSize=m_dataList.size();
    int insertLen=10;

    emit beginInsertRows(QModelIndex(), m_dataList.size(), m_dataList.size()+insertLen-1);

    QTime time=QTime::currentTime();
    for(int i=currentSize; i

(----------------完--------------)

你可能感兴趣的:(Qt)