QT中QtConcurrent创建并行线程的方法
阅读原文时间:2021年04月23日阅读:1

头文件中:

#include

#include

#include

protected:

bool event(QEvent *event);

/*

自定义的ProgressEvent结构体

*/

struct ProgressEvent : public QEvent

{

enum {EventId = QEvent::User};

explicit ProgressEvent(bool saved_, const DWORD &message_)

: QEvent(static_cast<QEvent::Type>(EventId)),

saved(saved_), message(message_) {}

const bool saved;

const DWORD message;

};

在类的成员函数中写:

QFuture<void> future = QtConcurrent::run(runVipNet,this,path);

//阻塞主线程直到计算完成

future.waitForFinished();

runVipNet是类外函数:

//

void runVipNet(QMainWindow *receiver,QString _path)

{

QApplication::postEvent(receiver,new ProgressEvent(true, (DWORD)QThread::currentThreadId()));

MainWindow* s = (MainWindow*) receiver;

//获取线程ID

s->addThreadID((DWORD)QThread::currentThreadId());

//运行外部exe

QProcess::startDetached(_path,QStringList());

}

//

bool MainWindow::event(QEvent *event)

{

if (event->type() == static_cast<QEvent::Type>(ProgressEvent::EventId))

{

ProgressEvent *progressEvent = static_cast(event);

Q_ASSERT(progressEvent);

ui->textBrowser->append(QString::number(progressEvent->message));

return true;

}

return QMainWindow::event(event);

}

/*

自定义的ProgressEvent结构体

*/

struct ProgressEvent : public QEvent

{

enum {EventId = QEvent::User};

explicit ProgressEvent(bool saved_, const DWORD &message_)

: QEvent(static_cast<QEvent::Type>(EventId)),

saved(saved_), message(message_) {}

const bool saved;

const DWORD message;

};

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章