前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qt 6中的异步操作

Qt 6中的异步操作

作者头像
Qt君
发布2023-03-17 13:57:20
1.2K0
发布2023-03-17 13:57:20
举报
文章被收录于专栏:跟Qt君学编程

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

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

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

  具体的函数操作:

代码语言:javascript
复制
QByteArray download(const QUrl &url);
QImage createImage(const QByteArray &data);
QImage processImage(const QImage &image);
void show(const QImage &image);

  代码实现:

代码语言:javascript
复制
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版本中可以这样操作。看起来是不是简便很多呢。

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-10-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档