zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Qt 6中的异步操作

Qt异步 操作
2023-06-13 09:17:28 时间

❝从Qt官网看到的一篇关于Qt 6的文章,分享给大家。❞

  我们先看看Qt 6版本以前「从网络中加载图片的一般操作步骤」

  1. 发出网络请求并等待,直到收到所有图像数据。
  2. 根据原始数据创建图像源。
  3. 处理图像。
  4. 显示图像。

  具体的函数操作:

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 
            });
  • 链接: https://www.qt.io/blog/asynchronous-apis-in-qt-6