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

发布于:2024-06-18 ⋅ 阅读:(124) ⋅ 点赞:(0)

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

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


网站公告

今日签到

点亮在社区的每一天
去签到