이 페이지에서

'Fetch More' 예제

'Fetch More' 예제는 요청에 따라 항목 뷰 모델에 항목을 추가하는 방법을 보여줍니다.

항목을 가져와 뷰 모델에 추가하는 애플리케이션

대규모(혹은 무한한) 데이터 세트가 있는 경우, 모델에 항목을 일괄적으로 추가해야 하며, 가급적이면 뷰에서 해당 항목이 필요할 때(즉, 뷰에 표시될 때)에만 추가해야 합니다.

이 예제에서는 디렉터리의 항목을 포함하는 항목 뷰 모델인 ` FileListModel `을 구현합니다. 또한 GUI를 설정하고 모델에 디렉터리를 전달하는 ` Window`도 있습니다.

UI는 루트 디렉터리의 내용을 보여주는 목록이 포함된 대화 상자로 구성되어 있습니다. 디렉터리는 더블 클릭하여 탐색할 수 있습니다.

하단에는 뷰가 모델에 추가 데이터를 요청할 때 메시지를 표시하는 로그 창이 있습니다.

이 기능을 테스트해 보려면, 대용량 디렉터리(예: /bin)로 이동한 뒤 화면 하단으로 스크롤해 보세요. 데이터가 불러오는 과정을 보여주는 로그 메시지가 표시됩니다.

FileListModel 의 코드를 살펴보겠습니다.

FileListModel 클래스 정의

FileListModel 은 QAbstractListModel 을 상속받으며, 디렉터리의 내용을 포함합니다. 이 클래스는 뷰에서 요청이 있을 때에만 자체적으로 항목을 추가합니다.

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;

    QFileInfo fileInfoAt(const QModelIndex &) const;

signals:
    void numberPopulated(const QString &path, int start, int number, int total);

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

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

private:
    QFileInfoList fileList;
    QString path;
    QFileIconProvider iconProvider;
    int fileCount = 0;
};

핵심은 QAbstractItemModel 에서 정의된 fetchMore() 및 canFetchMore() 함수를 재구현한 데 있습니다. 이 함수들은 아이템 뷰가 더 많은 아이템이 필요할 때 호출됩니다.

setDirPath() 함수는 모델이 처리할 디렉터리를 설정합니다. 모델에 항목을 일괄 추가할 때마다 numberPopulated() 를 반환합니다.

fileList 에는 모든 디렉터리 항목을 보관합니다. fileCount 는 모델에 추가된 항목의 수를 나타냅니다.

FileListModel 클래스 구현

먼저 setDirPath() 을 체크아웃합니다.

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

    beginResetModel();
    this->path = path;
    fileList = dir.entryInfoList(QDir::NoDot | QDir::AllEntries, QDir::Name);
    fileCount = 0;
    endResetModel();
}

QDir 을 사용하여 디렉터리의 내용을 가져옵니다. 모델에서 모든 항목(있는 경우)을 제거하고자 한다는 사실을 QAbstractItemModel 에 알려야 합니다.

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
        return false;
    return (fileCount < fileList.size());
}

canFetchMore() 함수는 뷰에서 더 많은 항목이 필요할 때 호출됩니다. 모델에 아직 추가하지 않은 항목이 남아 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

이제 fetchMore() 함수 자체를 살펴보겠습니다.

void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
        return;
    const int start = fileCount;
    const int remainder = int(fileList.size()) - start;
    const int itemsToFetch = qMin(batchSize, remainder);

    if (itemsToFetch <= 0)
        return;

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

    fileCount += itemsToFetch;

    endInsertRows();

    emit numberPopulated(path, start, itemsToFetch, int(fileList.size()));
}

먼저 가져올 항목의 수를 계산합니다. QAbstractItemModel 가 행 삽입을 제대로 처리하려면 beginInsertRows()와 endInsertRows()가 필수적입니다. 마지막으로 numberPopulated() 를 발산하면, Window 가 이를 수신합니다.

이 설명을 마무리하며, rowCount() 및 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 {};

    const int row = index.row();
    if (row >= fileList.size() || row < 0)
        return {};

    switch (role) {
    case Qt::DisplayRole:
        return fileList.at(row).fileName();
    case Qt::BackgroundRole: {
        const int batch = row / batchSize;
        const QPalette &palette = QGuiApplication::palette();
        return (batch % 2) != 0 ? palette.alternateBase() : palette.base();
    }
    case Qt::DecorationRole:
        return iconProvider.icon(fileList.at(row));
    }
    return {};
}

행 수는 지금까지 추가한 항목 수일 뿐이며, 즉 디렉터리의 항목 수와는 다르다는 점에 유의하십시오.

data() 에서는 fileList 에서 적절한 항목을 반환합니다. 또한 각 배치를 서로 다른 배경색으로 구분합니다.

코드 예제 @ code.qt.io

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