Fetch More Example

The user of the example can enter a directory in the Directory line edit. The contents of the directory will be listed in the list view below.

When you have large - or perhaps even infinite - data sets, you will need to add items to the model in batches, and preferably only when the items are needed by the view (i.e., when they are visible in the view).

In this example, we implement FileListModel - an item view model containing the entries of a directory. We also have Window, which sets up the GUI and feeds the model with directories.

Let's take a tour of FileListModel's code.

FileListModel Class Definition

The FileListModel inherits QAbstractListModel and contains the contents of a directory. It will add items to itself only when requested to do so by the view.

class FileListModel : public QAbstractListModel
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = 0);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

signals:
    void numberPopulated(int number);

public slots:
    void setDirPath(const QString &path);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QStringList fileList;
    int fileCount;
};

The secret lies in the reimplementation of fetchMore() and canFetchMore() from QAbstractItemModel. These functions are called by the item view when it needs more items.

The setDirPath() function sets the directory the model will work on. We emit numberPopulated() each time we add a batch of items to the model.

We keep all directory entries in fileList. fileCount is the number of items that have been added to the model.

FileListModel Class Implementation

We start by checking out the setDirPath().

void FileListModel::setDirPath(const QString &path)
{
    QDir dir(path);

    beginResetModel();
    fileList = dir.entryList();
    fileCount = 0;
    endResetModel();
}

We use a QDir to get the contents of the directory. We need to inform QAbstractItemModel that we want to remove all items - if any - from the model.

bool FileListModel::canFetchMore(const QModelIndex & /* index */) const
{
    if (fileCount < fileList.size())
        return true;
    else
        return false;
}

The canFetchMore() function is called by the view when it needs more items. We return true if there still are entries that we have not added to the model; otherwise, we return false.

And now, the fetchMore() function itself:

void FileListModel::fetchMore(const QModelIndex & /* index */)
{
    int remainder = fileList.size() - fileCount;
    int itemsToFetch = qMin(100, remainder);

    beginInsertRows(QModelIndex(), fileCount, fileCount+itemsToFetch-1);

    fileCount += itemsToFetch;

    endInsertRows();

    emit numberPopulated(itemsToFetch);
}

We first calculate the number of items to fetch. beginInsertRows() and endInsertRows() are mandatory for QAbstractItemModel to keep up with the row insertions. Finally, we emit numberPopulated(), which is picked up by Window.

To complete the tour, we also look at rowCount() and data().

int FileListModel::rowCount(const QModelIndex & /* parent */) const
{
    return fileCount;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() >= fileList.size() || index.row() < 0)
        return QVariant();

    if (role == Qt::DisplayRole) {
        return fileList.at(index.row());
    } else if (role == Qt::BackgroundRole) {
        int batch = (index.row() / 100) % 2;
        if (batch == 0)
            return qApp->palette().base();
        else
            return qApp->palette().alternateBase();
    }
    return QVariant();
}

Notice that the row count is only the items we have added so far, i.e., not the number of entries in the directory.

In data(), we return the appropriate entry from the fileList. We also separate the batches with a different background color.

Files:

© 2019 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.