❝从Qt官网看到的一篇关于Qt 6的文章,分享给大家。❞
我们先看看Qt 6版本以前「从网络中加载图片的一般操作步骤」。
具体的函数操作:
QByteArray download(const QUrl &url);
QImage createImage(const QByteArray &data);
QImage processImage(const QImage &image);
void show(const QImage &image);
代码实现:
void loadImage(const QUrl &url) {
QFuture data = QtConcurrent::run(download, url);
QFutureWatcher dataWatcher;
dataWatcher.setFuture(data);
connect(&dataWatcher, &QFutureWatcher ::finished, this, [=] {
// handle possible errors
// ...
QImage image = createImage(data);
// Process the image
// ...
QFuture processedImage = QtConcurrent::run(processImage, image);
QFutureWatcher<QImage> imageWatcher;
imageWatcher.setFuture(processedImage);
connect(&imageWatcher, &QFutureWatcher::finished, this, [=] {
// handle possible errors
// ...
show(processedImage);
});
});
}
Qt 6版本中可以这样操作。看起来是不是简便很多呢。
auto future = QtConcurrent::run(download, url)
.then(createImage)
.then(processImage)
.then(show)
.onFailed([](QNetworkReply::NetworkError) { // 错误处理
// handle network errors
})
.onFailed([](ImageProcessingError) { // 错误处理
// handle image processing errors
})
.onFailed([] { // 错误处理
// handle any other error
});