当前位置: 首页 > news >正文

QT不阻塞UI的方式

方法1:QtConcurrent

#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>
#include <QDebug>void longRunningTask() {// 模拟耗时操作QThread::sleep(5);
}void startTask() {QFuture<void> future = QtConcurrent::run(longRunningTask);QFutureWatcher<void> *watcher = new QFutureWatcher<void>();QObject::connect(watcher, &QFutureWatcher<void>::finished, []() {qDebug() << "Task finished, update UI here.";// 在这里更新UI});watcher->setFuture(future);
}

方法2:QEventLoop

QEventLoop loop;
QTimer::singleShot(milliseconds, &loop, &QEventLoop::quit);
loop.exec();

方法3:thread

std::thread th1(function);
th1.detach();

方法4:async

#include <iostream>
#include <future>
#include <chrono>// 模拟一个耗时的计算任务
int longRunningTask(int id, int duration) {std::cout << "Task " << id << " started, will take " << duration << " seconds." << std::endl;std::this_thread::sleep_for(std::chrono::seconds(duration)); // 模拟耗时任务std::cout << "Task " << id << " completed." << std::endl;return id * duration;  // 返回一些计算结果
}int main() {// 使用std::async启动两个异步任务std::future<int> result1 = std::async(std::launch::async, longRunningTask, 1, 3);std::future<int> result2 = std::async(std::launch::async, longRunningTask, 2, 2);std::cout << "Main thread continues to run..." << std::endl;// 在主线程做其他事情for (int i = 0; i < 5; ++i) {std::cout << "Main thread working..." << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));}// 获取异步任务的结果int value1 = result1.get();  // 这时如果任务尚未完成,主线程会阻塞在此int value2 = result2.get();std::cout << "Result of task 1: " << value1 << std::endl;std::cout << "Result of task 2: " << value2 << std::endl;return 0;
}
http://www.lryc.cn/news/421290.html

相关文章:

  • 鸿蒙HarmonyOS开发:常用布局及实用技巧
  • 【解答】洛必达法则的使用条件及常见错误,洛必达法则的适用条件,常见的易错点,2022数一第一题例题
  • 使用Python下载飞书共享表格数据教程
  • 【C++】protobuf的简单使用(通讯录例子)
  • Apple 智能基础语言模型
  • GreptimeDB融资数百万美元; Oracle提供免费长期MySQL; 谷歌大模型支持云数据库问题洞察
  • Java中的抽象类与接口
  • 云计算概念以及与云服务的区别
  • Netty技术全解析:LengthFieldBaseFrameDecoder类深度解析
  • 深入InnoDB核心:揭秘B+树在数据库索引中的高效应用
  • c++(面向对象的性质:抽象,封装,继承,多态)
  • java基础学习笔记1
  • [VBA]使用VBA在Excel中 操作 形状shape 对象
  • Apache POI 实现 Excel 表格下载
  • 大华嵌入式面试题大全及参考答案(2万字长文)
  • C语言——查漏补缺
  • Python | Leetcode Python题解之第328题奇偶链表
  • 吉瑞外卖笔记
  • Perl套接字编程指南:构建网络通信应用
  • 达梦数据库(十) -------- mybatis-plus 整合达梦时,自动生成的 sql 语句报错
  • 停止项目大小调整,开始搜索层自动缩放!
  • VScode的环境编译器选择
  • 在Linux中通过docker安装和配置supervisor进程守护
  • CanMV-K230自学笔记系列(不定期更新)
  • [GXYCTF2019]禁止套娃-使用无参数读文件
  • SpringBoot+MyBatis模板
  • Springboot 定时任务 @EnableScheduling @Scheduled
  • STM32F407ZET6使用LCD(9341)
  • 动手学深度学习7.3 网络中的网络(NiN)-笔记练习(PyTorch)
  • SQL语言-select的使用方法