Fetch More Example

The Fetch More example shows how to add items to an item view model on demand.

This example consists of a dialog where you can enter a directory name in the Directory edit field. The application loads and visualizes all files it finds as you are typing. It is not required to press [Enter] to launch the search.

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 = nullptr);

    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 &parent) const
{
    if (parent.isValid())
        return false;
    return (fileCount < fileList.size());
}

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 &parent)
{
    if (parent.isValid())
        return;
    int remainder = fileList.size() - fileCount;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
        return;

    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 parent.isValid() ? 0 : 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.

Example project @ code.qt.io

© 2020 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.