声明一个处理函数;int timeTask();
头文件:
#include <QtConcurrent>
#include <QFuture>
并发处理改函数的任务,直到处理完成:
QFuture<int> ft = QtConcurrent::run(this, &ch72_concurrent::timeTask);
while (!ft.isFinished())
{
QApplication::processEvents(QEventLoop::AllEvents, 30);
}
带参数的函数:
将参数写在后面
QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);
通过QFutureWatcher获取返回值:
QFutureWatcher<int>* fw = new QFutureWatcher<int>;
connect(fw, &QFutureWatcher<int>::finished, [&]{
qDebug() << "QFutureWatcher finished";
qDebug() << "result = " << fw->result();
});
QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);
fw->setFuture(ft);
while (!ft.isFinished())
{
QApplication::processEvents(QEventLoop::AllEvents, 30);
}
完整代码
#include "ch74.h"
#include <QDebug>
#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>
ch74::ch74(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
ch74::~ch74()
{}
int ch74::timeTask(int& num1, int& num2)
{
for (int i = 0; i < 1000; i++)
{
num1++;
num2++;
qDebug() << num1;
qDebug() << num2;
}
return num1 + num2;
}
void ch74::on_pushButton_clicked()
{
int num1 = 0;
int num2 = 0;
QFutureWatcher<int>* fw = new QFutureWatcher<int>;
connect(fw, &QFutureWatcher<int>::finished, [&]{
qDebug() << "QFutureWatcher finished";
qDebug() << "result = " << fw->result();
});
QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);
fw->setFuture(ft);
while (!ft.isFinished())
{
QApplication::processEvents(QEventLoop::AllEvents, 30);
}
}