diff options
| author | Otto Ryynänen <otto.ryynanen@qt.io> | 2025-03-31 10:18:10 +0300 |
|---|---|---|
| committer | Otto Ryynänen <otto.ryynanen@qt.io> | 2025-04-04 19:31:49 +0300 |
| commit | 0e92a8e0683e2d388a61aac85509a8efbc16cd01 (patch) | |
| tree | 3b5588fb8f6e7ebdeff23b1cb6867941e00cdf51 /examples/quick/models/threadedfetchmore/fetchworker.cpp | |
| parent | a951832b74749cde7832ee906df087ac857f5cbd (diff) | |
Introduce threaded fetchmore example
Added an example of combining QThread and QAbstractItemModel - a feat
that our customers ask every now and then
Task-number: QTBUG-135351
Pick-to: 6.8 6.9
Change-Id: I476e7121361e4d85c2d87eb663f0389a337a3085
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
Diffstat (limited to 'examples/quick/models/threadedfetchmore/fetchworker.cpp')
| -rw-r--r-- | examples/quick/models/threadedfetchmore/fetchworker.cpp | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/examples/quick/models/threadedfetchmore/fetchworker.cpp b/examples/quick/models/threadedfetchmore/fetchworker.cpp new file mode 100644 index 0000000000..33b0272914 --- /dev/null +++ b/examples/quick/models/threadedfetchmore/fetchworker.cpp @@ -0,0 +1,46 @@ +// Copyright (C) 2025 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include "fetchworker.h" + +#include <QThread> + +static constexpr int s_fetchBlockSize{50}; +static constexpr int s_maximumListSize{s_fetchBlockSize * 10}; +static constexpr int s_sleepIterations{20}; +static constexpr std::chrono::milliseconds s_sleepInterval{100}; + +FetchWorker::FetchWorker(QObject *parent) + : QObject{parent} +{} + +void FetchWorker::fetchDataBlock() +{ + if (m_existingItemsCount < s_maximumListSize) { + QList<DataBlock> itemsToSend = slowDataConstruction(m_existingItemsCount); + m_existingItemsCount += itemsToSend.size(); + emit dataFetched(itemsToSend); + } + if (m_existingItemsCount >= s_maximumListSize) + emit noMoreToFetch(); +} + +QList<FetchWorker::DataBlock> FetchWorker::slowDataConstruction(int fromIndex) +{ + // Block for two seconds to mimic slow data source, while allowing interruption in case of application close + for (int iterations = s_sleepIterations; + iterations > 0 && !QThread::currentThread()->isInterruptionRequested(); + --iterations) { + QThread::sleep(s_sleepInterval); + } + QList<DataBlock> returnValues; + returnValues.reserve(s_fetchBlockSize); + int number = fromIndex; + for (int blocks = 0; blocks < s_fetchBlockSize; ++blocks) { + ++number; + returnValues.append({QStringLiteral("Contact %1 name").arg(number), + QStringLiteral("Contact %1 telephone").arg(number), + number}); + } + return returnValues; +} |
