【Qt】QCoreApplication::processEvents的简单使用

QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

cpp 复制代码
void Widget::on_pushButton_clicked()
{
    qDebug() << "pushButton 1 ... " ;

    // 模拟一个长时间运行的循环
    for(int i = 0; i < 10; ++i) {
        qDebug() << "Loop iteration 1 " << i;
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100); // 处理事件,最多处理100毫秒
        // 假设这里有一些耗时的操作...
        QThread::sleep(1); // 模拟耗时操作,让当前线程休眠1秒
    }
}

void Widget::on_pushButton_2_clicked()
{
    qDebug() << "pushButton 2 ... " ;
    // 模拟一个长时间运行的循环
    for(int i = 0; i < 10; ++i) {
        qDebug() << "Loop iteration 2 " << i;
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100); // 处理事件,最多处理100毫秒
        // 假设这里有一些耗时的操作...
        QThread::msleep(500); // 模拟耗时操作,让当前线程休眠0.5秒
    }
}

运行过程中点击按键1 后点击按键2,然后再点击按键1。整个过程,按键是可以正常的点击的,不会出现未响应的情况。

运行结果:

pushButton 1 ...

Loop iteration 1 0

Loop iteration 1 1

Loop iteration 1 2

Loop iteration 1 3

pushButton 2 ...

Loop iteration 2 0

Loop iteration 2 1

Loop iteration 2 2

Loop iteration 2 3

Loop iteration 2 4

pushButton 1 ...

Loop iteration 1 0

Loop iteration 1 1

Loop iteration 1 2

Loop iteration 1 3

Loop iteration 1 4

Loop iteration 1 5

Loop iteration 1 6

Loop iteration 1 7

Loop iteration 1 8

Loop iteration 1 9

Loop iteration 2 5

Loop iteration 2 6

Loop iteration 2 7

Loop iteration 2 8

Loop iteration 2 9

Loop iteration 1 4

Loop iteration 1 5

Loop iteration 1 6

Loop iteration 1 7

Loop iteration 1 8

Loop iteration 1 9

相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼3 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark3 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her13 天前
并查集-听课笔记
笔记·算法·并查集
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
码流子3 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构