-
Notifications
You must be signed in to change notification settings - Fork 363
/
mainwindow.cpp
57 lines (48 loc) · 1.75 KB
/
mainwindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtConcurrent>
#include <QThread>
#include <QDateTime>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//关联future结束信号,注意watcher一次只能绑定一个future
connect(&theWatcher,&QFutureWatcher<QString>::finished,this,[this]{
qDebug()<<"Future finished"<<QThread::currentThread();
//结束之后从future获取结果
qDebug()<<"Future result"<<theWatcher.future().result();
});
//点击按钮从concurrent生成一个future
connect(ui->btnA,&QPushButton::clicked,[this]{
qDebug()<<"A click"<<QThread::currentThread();
//可以传递参数给线程处理
QFuture<QString> future=QtConcurrent::run([](const QString &arg){
qDebug()<<"A begin"<<QThread::currentThread();
QThread::msleep(1000);
return QString("This is A result.%1").arg(arg);
},
QString("Gong Jian Bo."));
theWatcher.setFuture(future);
});
//点击按钮从future interface生成一个future
connect(ui->btnB,&QPushButton::clicked,[this]{
qDebug()<<"B click"<<QThread::currentThread();
QtConcurrent::run([this]{
theInterface.reportStarted();
qDebug()<<"B begin"<<QThread::currentThread();
QThread::msleep(1000);
theInterface.reportResult(QString("This is B result"));
theInterface.reportFinished();
});
//可以把interface和线程封装到一个类中,如配合QRunnable字类
theWatcher.setFuture(theInterface.future());
});
}
MainWindow::~MainWindow()
{
theWatcher.waitForFinished();
delete ui;
}