summaryrefslogtreecommitdiffstats
path: root/examples/qtconcurrent/imagescaling
diff options
context:
space:
mode:
Diffstat (limited to 'examples/qtconcurrent/imagescaling')
-rw-r--r--examples/qtconcurrent/imagescaling/CMakeLists.txt48
-rw-r--r--examples/qtconcurrent/imagescaling/doc/images/imagescaling.webpbin0 -> 46826 bytes
-rw-r--r--examples/qtconcurrent/imagescaling/doc/images/imagescaling_example.pngbin21049 -> 0 bytes
-rw-r--r--examples/qtconcurrent/imagescaling/doc/src/qtconcurrent-imagescaling.qdoc142
-rw-r--r--examples/qtconcurrent/imagescaling/downloaddialog.cpp51
-rw-r--r--examples/qtconcurrent/imagescaling/downloaddialog.h51
-rw-r--r--examples/qtconcurrent/imagescaling/imagescaling.cpp150
-rw-r--r--examples/qtconcurrent/imagescaling/imagescaling.h62
-rw-r--r--examples/qtconcurrent/imagescaling/main.cpp58
9 files changed, 178 insertions, 384 deletions
diff --git a/examples/qtconcurrent/imagescaling/CMakeLists.txt b/examples/qtconcurrent/imagescaling/CMakeLists.txt
index bb1677983d..d053d04fc1 100644
--- a/examples/qtconcurrent/imagescaling/CMakeLists.txt
+++ b/examples/qtconcurrent/imagescaling/CMakeLists.txt
@@ -1,45 +1,41 @@
-# Generated from imagescaling.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(imagescaling LANGUAGES CXX)
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
+find_package(Qt6 REQUIRED COMPONENTS Concurrent Core Gui Network Widgets)
-set(CMAKE_AUTOMOC ON)
-set(CMAKE_AUTORCC ON)
-set(CMAKE_AUTOUIC ON)
-
-if(NOT DEFINED INSTALL_EXAMPLESDIR)
- set(INSTALL_EXAMPLESDIR "examples")
-endif()
-
-set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/qtconcurrent/imagescaling")
-
-find_package(Qt6 COMPONENTS Core)
-find_package(Qt6 COMPONENTS Gui)
-find_package(Qt6 COMPONENTS Concurrent)
-find_package(Qt6 COMPONENTS Widgets)
-find_package(Qt6 COMPONENTS Network)
+qt_standard_project_setup()
qt_add_executable(imagescaling
downloaddialog.cpp downloaddialog.h downloaddialog.ui
imagescaling.cpp imagescaling.h
main.cpp
)
+
set_target_properties(imagescaling PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
-target_link_libraries(imagescaling PUBLIC
- Qt::Concurrent
- Qt::Core
- Qt::Gui
- Qt::Network
- Qt::Widgets
+
+target_link_libraries(imagescaling PRIVATE
+ Qt6::Concurrent
+ Qt6::Core
+ Qt6::Gui
+ Qt6::Network
+ Qt6::Widgets
)
install(TARGETS imagescaling
- RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
- BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
- LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
+ BUNDLE DESTINATION .
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+)
+
+qt_generate_deploy_app_script(
+ TARGET imagescaling
+ OUTPUT_SCRIPT deploy_script
+ NO_UNSUPPORTED_PLATFORM_ERROR
)
+install(SCRIPT ${deploy_script})
diff --git a/examples/qtconcurrent/imagescaling/doc/images/imagescaling.webp b/examples/qtconcurrent/imagescaling/doc/images/imagescaling.webp
new file mode 100644
index 0000000000..56999faaa7
--- /dev/null
+++ b/examples/qtconcurrent/imagescaling/doc/images/imagescaling.webp
Binary files differ
diff --git a/examples/qtconcurrent/imagescaling/doc/images/imagescaling_example.png b/examples/qtconcurrent/imagescaling/doc/images/imagescaling_example.png
deleted file mode 100644
index a3860e1974..0000000000
--- a/examples/qtconcurrent/imagescaling/doc/images/imagescaling_example.png
+++ /dev/null
Binary files differ
diff --git a/examples/qtconcurrent/imagescaling/doc/src/qtconcurrent-imagescaling.qdoc b/examples/qtconcurrent/imagescaling/doc/src/qtconcurrent-imagescaling.qdoc
index 8814c826ed..499cb165c8 100644
--- a/examples/qtconcurrent/imagescaling/doc/src/qtconcurrent-imagescaling.qdoc
+++ b/examples/qtconcurrent/imagescaling/doc/src/qtconcurrent-imagescaling.qdoc
@@ -1,41 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\example imagescaling
- \title Image Scaling Example
- \brief Demonstrates how to asynchronously download and scale images.
+ \meta tags {widgets, threads, network}
+ \title Image Scaling
\ingroup qtconcurrentexamples
- \image imagescaling_example.png
+ \examplecategory {Networking}
+ \brief Demonstrates how to asynchronously download and scale images.
- This example shows how to use the QFuture and QPromise classes to download a
- collection of images from the network and scale them, without blocking the UI.
+ This example shows how to use the QFuture, QPromise, and QFutureWatcher
+ classes to download a collection of images from the network and scale them,
+ without blocking the UI.
- The application consists of the the following steps:
+ \image imagescaling.webp
+
+ The application consists of the following steps:
\list 1
\li Download images form the list of URLs specified by the user.
@@ -68,7 +48,6 @@
And here starts the interesting part:
- \dots
\snippet imagescaling/imagescaling.cpp 11
\dots
@@ -78,12 +57,14 @@
QNetworkReply::finished() signal is emitted. This allows us to attach continuations
and failure handlers, as it is done in the example.
- In the continuation attached via \b{.then()}, we check if the user has requested to
- cancel the download. If that's the case, we stop processing the request. By calling
- the \c QPromise::finish() method, we notify the user that processing has been finished.
+ In the continuation attached via \l{QFuture::then}{.then()}, we check if the
+ user has requested to cancel the download. If that's the case, we stop
+ processing the request. By calling the \l QPromise::finish() method, we notify
+ the user that processing has been finished.
In case the network request has ended with an error, we throw an exception. The
- exception will be handled in the failure handler attached using the \b{.onFailed()}
- method. Note that we have two failure handlers: the first one captures the network
+ exception will be handled in the failure handler attached using the
+ \l{QFuture::onFailed}{.onFailed()} method.
+ Note that we have two failure handlers: the first one captures the network
errors, the second one all other exceptions thrown during the execution. Both handlers
save the exception inside the promise object (to be handled by the caller of the
\c download() method) and report that the computation has finished. Also note that,
@@ -105,7 +86,7 @@
we need to copy and use the promise object in multiple places simultaneously. Hence,
a QSharedPointer is used.
- \c download() method is called from the \c QImage::process method. It is invoked
+ The \c download() method is called from the \c Images::process method. It is invoked
when the user presses the \e {"Add URLs"} button:
\dots
@@ -121,38 +102,20 @@
\snippet imagescaling/imagescaling.cpp 3
\dots
- Next, we attach a continuation to handle the scaling step:
+ Next, we attach a continuation to handle the scaling step.
+ More on that later:
\snippet imagescaling/imagescaling.cpp 4
\dots
- Since the scaling may be computationally heavy, and we don't want to block the main
- thread, we pass the \c QtFuture::Launch::Async option, to launch the scaling step in
- a new thread. The \c scaled() method returns a list of the scaled images to the next
- step, which takes care of showing images in the layout.
+ After that we attach \l {QFuture::}{onCanceled()} and \l {QFuture::}{onFailed()}
+ handlers:
- Note that \c updateStatus() is called through QMetaObject::invokeMethod(),
- because it updates the UI and needs to be invoked from the main thread.
-
- \dots
\snippet imagescaling/imagescaling.cpp 5
\dots
- For the same reason \c showImages() also needs to be invoked from the main thread, so
- we pass \c this as a context to \c .then(). By default, \c .then() is launched in the
- parent's thread, but if a context object is specified, it is launched in the context
- object's thread.
-
- Then we add cancellation and failure handlers:
-
- \dots
- \snippet imagescaling/imagescaling.cpp 6
-
- We don't need to specify the context anymore, because \c .onCanceled() and the next
- handlers will be launched in their parent's context.
-
- The handler attached via the \c .onCanceled() method will be called if the user has
- pressed the \e "Cancel" button:
+ The handler attached via the \l {QFuture::onCanceled}{.onCanceled()} method
+ will be called if the user has pressed the \e "Cancel" button:
\dots
\snippet imagescaling/imagescaling.cpp 2
@@ -162,14 +125,57 @@
\snippet imagescaling/imagescaling.cpp 7
- The handlers attached via \c .onFailed() method will be called in case an
- error occurred during one of the previous steps. For example, if a network error
- has been saved inside the promise during the download step, it will be propagated to
- the handler that takes \c QNetworkReply::NetworkError as argument. A failure can
- happen also during the scaling step:
+ The handlers attached via \l {QFuture::onFailed}{.onFailed()} method will be
+ called in case an error occurred during one of the previous steps.
+ For example, if a network error has been saved inside the promise during the
+ download step, it will be propagated to the handler that takes
+ \l QNetworkReply::NetworkError as argument.
+
+ If the \c downloadFuture is not canceled, and didn't report any error, the
+ scaling continuation is executed.
+
+ Since the scaling may be computationally heavy, and we don't want to block
+ the main thread, we use \l QtConcurrent::run(), to launch the scaling step
+ in a new thread.
+
+ \snippet imagescaling/imagescaling.cpp 16
+
+ Since the scaling is launched in a separate thread, the user can potentially
+ decide to close the application while the scaling operation is in progress.
+ To handle such situations gracefully, we pass the \l QFuture returned by
+ \l QtConcurrent::run() to the \l QFutureWatcher instance.
+
+ The watcher's \l QFutureWatcher::finished signal is connected to the
+ \c Images::scaleFinished slot:
+
+ \snippet imagescaling/imagescaling.cpp 6
+
+ This slot is responsible for showing the scaled images in the UI, and also
+ for handling the errors that could potentially happen during scaling:
+
+ \snippet imagescaling/imagescaling.cpp 15
+
+ The error reporting is implemented by returning an optional from the
+ \c Images::scaled() method:
\snippet imagescaling/imagescaling.cpp 14
+ The \c Images::OptionalImages type here is simply a typedef for \c std::optional:
+
+ \snippet imagescaling/imagescaling.h 1
+
+ \note We cannot handle the errors from the async scaling operation using
+ the \l {QFuture::onFailed}{.onFailed()} handler, because the handler needs
+ to be executed in the context of \c Images object in the UI thread.
+ If the user closes the application while the async computation is done,
+ the \c Images object will be destroyed, and accessing its members from the
+ continuation will lead to a crash. Using \l QFutureWatcher and its signals
+ allows us to avoid the problem, because the signals are disconnected when
+ the \l QFutureWatcher is destroyed, so the related slots will never be
+ executed in a destroyed context.
+
The rest of the code is straightforward, you can check the example project for
more details.
+
+ \include examples-run.qdocinc
*/
diff --git a/examples/qtconcurrent/imagescaling/downloaddialog.cpp b/examples/qtconcurrent/imagescaling/downloaddialog.cpp
index 2f2f901b0e..c3ec550038 100644
--- a/examples/qtconcurrent/imagescaling/downloaddialog.cpp
+++ b/examples/qtconcurrent/imagescaling/downloaddialog.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "downloaddialog.h"
#include "ui_downloaddialog.h"
diff --git a/examples/qtconcurrent/imagescaling/downloaddialog.h b/examples/qtconcurrent/imagescaling/downloaddialog.h
index 9e5d478d7d..e4a6482907 100644
--- a/examples/qtconcurrent/imagescaling/downloaddialog.h
+++ b/examples/qtconcurrent/imagescaling/downloaddialog.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef DOWNLOADDIALOG_H
#define DOWNLOADDIALOG_H
diff --git a/examples/qtconcurrent/imagescaling/imagescaling.cpp b/examples/qtconcurrent/imagescaling/imagescaling.cpp
index 66bb0686c3..f380ae9d90 100644
--- a/examples/qtconcurrent/imagescaling/imagescaling.cpp
+++ b/examples/qtconcurrent/imagescaling/imagescaling.cpp
@@ -1,64 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
#include "imagescaling.h"
#include "downloaddialog.h"
#include <QNetworkReply>
-#include <qmath.h>
-
-#include <functional>
-
-Images::Images(QWidget *parent) : QWidget(parent), downloadDialog(new DownloadDialog())
+Images::Images(QWidget *parent) : QWidget(parent), downloadDialog(new DownloadDialog(this))
{
- setWindowTitle(tr("Image downloading and scaling example"));
resize(800, 600);
addUrlsButton = new QPushButton(tr("Add URLs"));
@@ -87,6 +36,11 @@ Images::Images(QWidget *parent) : QWidget(parent), downloadDialog(new DownloadDi
mainLayout->addStretch();
mainLayout->addWidget(statusBar);
setLayout(mainLayout);
+
+//! [6]
+ connect(&scalingWatcher, &QFutureWatcher<QList<QImage>>::finished,
+ this, &Images::scaleFinished);
+//! [6]
}
Images::~Images()
@@ -99,6 +53,7 @@ void Images::process()
{
// Clean previous state
replies.clear();
+ addUrlsButton->setEnabled(false);
if (downloadDialog->exec() == QDialog::Accepted) {
@@ -114,33 +69,34 @@ void Images::process()
statusBar->showMessage(tr("Downloading..."));
//! [3]
-//! [4]
- downloadFuture.then([this](auto) { cancelButton->setEnabled(false); })
- .then(QtFuture::Launch::Async,
- [this] {
- QMetaObject::invokeMethod(this,
- [this] { updateStatus(tr("Scaling...")); });
- return scaled();
- })
-//! [4]
-//! [5]
- .then(this, [this](const QList<QImage> &scaled) {
- showImages(scaled);
- updateStatus(tr("Finished"));
+ //! [4]
+ downloadFuture
+ .then([this](auto) {
+ cancelButton->setEnabled(false);
+ updateStatus(tr("Scaling..."));
+ //! [16]
+ scalingWatcher.setFuture(QtConcurrent::run(Images::scaled,
+ downloadFuture.results()));
+ //! [16]
+ })
+ //! [4]
+ //! [5]
+ .onCanceled([this] {
+ updateStatus(tr("Download has been canceled."));
})
-//! [5]
-//! [6]
- .onCanceled([this] { updateStatus(tr("Download has been canceled.")); })
.onFailed([this](QNetworkReply::NetworkError error) {
updateStatus(tr("Download finished with error: %1").arg(error));
-
// Abort all pending requests
abortDownload();
})
- .onFailed([this](const std::exception& ex) {
+ .onFailed([this](const std::exception &ex) {
updateStatus(tr(ex.what()));
+ })
+ //! [5]
+ .then([this]() {
+ cancelButton->setEnabled(false);
+ addUrlsButton->setEnabled(true);
});
-//! [6]
}
}
@@ -154,22 +110,37 @@ void Images::cancel()
}
//! [7]
+//! [15]
+void Images::scaleFinished()
+{
+ const OptionalImages result = scalingWatcher.result();
+ if (result.has_value()) {
+ const auto scaled = result.value();
+ showImages(scaled);
+ updateStatus(tr("Finished"));
+ } else {
+ updateStatus(tr("Failed to extract image data."));
+ }
+ addUrlsButton->setEnabled(true);
+}
+//! [15]
+
//! [8]
QFuture<QByteArray> Images::download(const QList<QUrl> &urls)
-//! [8]
{
+//! [8]
//! [9]
QSharedPointer<QPromise<QByteArray>> promise(new QPromise<QByteArray>());
promise->start();
//! [9]
-//! [10]
- for (auto url : urls) {
+ //! [10]
+ for (const auto &url : urls) {
QSharedPointer<QNetworkReply> reply(qnam.get(QNetworkRequest(url)));
replies.push_back(reply);
-//! [10]
+ //! [10]
-//! [11]
+ //! [11]
QtFuture::connect(reply.get(), &QNetworkReply::finished).then([=] {
if (promise->isCanceled()) {
if (!promise->future().isFinished())
@@ -181,25 +152,24 @@ QFuture<QByteArray> Images::download(const QList<QUrl> &urls)
if (!promise->future().isFinished())
throw reply->error();
}
-//! [12]
+ //! [12]
promise->addResult(reply->readAll());
// Report finished on the last download
- if (promise->future().resultCount() == urls.size()) {
+ if (promise->future().resultCount() == urls.size())
promise->finish();
- }
-//! [12]
- }).onFailed([=] (QNetworkReply::NetworkError error) {
+ //! [12]
+ }).onFailed([promise] (QNetworkReply::NetworkError error) {
promise->setException(std::make_exception_ptr(error));
promise->finish();
- }).onFailed([=] {
+ }).onFailed([promise] {
const auto ex = std::make_exception_ptr(
std::runtime_error("Unknown error occurred while downloading."));
promise->setException(ex);
promise->finish();
});
}
-//! [11]
+ //! [11]
//! [13]
return promise->future();
@@ -207,15 +177,14 @@ QFuture<QByteArray> Images::download(const QList<QUrl> &urls)
//! [13]
//! [14]
-QList<QImage> Images::scaled() const
+Images::OptionalImages Images::scaled(const QList<QByteArray> &data)
{
QList<QImage> scaled;
- const auto data = downloadFuture.results();
- for (auto imgData : data) {
+ for (const auto &imgData : data) {
QImage image;
image.loadFromData(imgData);
if (image.isNull())
- throw std::runtime_error("Failed to load image.");
+ return std::nullopt;
scaled.push_back(image.scaled(100, 100, Qt::KeepAspectRatio));
}
@@ -238,6 +207,7 @@ void Images::initLayout(qsizetype count)
QLayoutItem *child;
while ((child = imagesLayout->takeAt(0)) != nullptr) {
child->widget()->setParent(nullptr);
+ delete child->widget();
delete child;
}
labels.clear();
diff --git a/examples/qtconcurrent/imagescaling/imagescaling.h b/examples/qtconcurrent/imagescaling/imagescaling.h
index 0c0d90870e..bc25161a85 100644
--- a/examples/qtconcurrent/imagescaling/imagescaling.h
+++ b/examples/qtconcurrent/imagescaling/imagescaling.h
@@ -1,58 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef IMAGESCALING_H
#define IMAGESCALING_H
#include <QtWidgets>
#include <QtConcurrent>
#include <QNetworkAccessManager>
+#include <optional>
class DownloadDialog;
class Images : public QWidget
@@ -65,7 +19,6 @@ public:
void initLayout(qsizetype count);
QFuture<QByteArray> download(const QList<QUrl> &urls);
- QList<QImage> scaled() const;
void updateStatus(const QString &msg);
void showImages(const QList<QImage> &images);
void abortDownload();
@@ -74,7 +27,15 @@ public slots:
void process();
void cancel();
+private slots:
+ void scaleFinished();
+
private:
+ //! [1]
+ using OptionalImages = std::optional<QList<QImage>>;
+ //! [1]
+ static OptionalImages scaled(const QList<QByteArray> &data);
+
QPushButton *addUrlsButton;
QPushButton *cancelButton;
QVBoxLayout *mainLayout;
@@ -86,6 +47,7 @@ private:
QNetworkAccessManager qnam;
QList<QSharedPointer<QNetworkReply>> replies;
QFuture<QByteArray> downloadFuture;
+ QFutureWatcher<OptionalImages> scalingWatcher;
};
#endif // IMAGESCALING_H
diff --git a/examples/qtconcurrent/imagescaling/main.cpp b/examples/qtconcurrent/imagescaling/main.cpp
index 01390499f5..67b543a961 100644
--- a/examples/qtconcurrent/imagescaling/main.cpp
+++ b/examples/qtconcurrent/imagescaling/main.cpp
@@ -1,62 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include <QtWidgets>
-#include <QtConcurrent>
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "imagescaling.h"
+#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc,argv);
+ app.setOrganizationName("QtProject");
+ app.setApplicationName(QObject::tr("Image Downloading and Scaling"));
Images imageView;
+ imageView.setWindowTitle(QObject::tr("Image Downloading and Scaling"));
imageView.show();
return app.exec();