QT不阻塞UI的方式

发布于:2024-08-11 ⋅ 阅读:(131) ⋅ 点赞:(0)

方法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;
}


网站公告

今日签到

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