Qt文档阅读笔记-QtConcurrent Progress Dialog Example解析
生活随笔
收集整理的這篇文章主要介紹了
Qt文档阅读笔记-QtConcurrent Progress Dialog Example解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這篇展示了如何監聽任務的進度。
QtConcurrent Progress Dialog使用QFutrueWathcer類去監聽任務進程進展。
代碼如下:
progressdialog.pro
QT += concurrent widgets CONFIG += consoleSOURCES += main.cpptarget.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/progressdialog INSTALLS += targetmain.cpp
#include <QtWidgets> #include <QtConcurrent>#include <functional>using namespace QtConcurrent;int main(int argc, char **argv) {QApplication app(argc, argv);const int iterations = 20;// Prepare the vector.QVector<int> vector;for (int i = 0; i < iterations; ++i)vector.append(i);// Create a progress dialog.QProgressDialog dialog;dialog.setLabelText(QString("Progressing using %1 thread(s)...").arg(QThread::idealThreadCount()));// Create a QFutureWatcher and connect signals and slots.QFutureWatcher<void> futureWatcher;QObject::connect(&futureWatcher, &QFutureWatcher<void>::finished, &dialog, &QProgressDialog::reset);QObject::connect(&dialog, &QProgressDialog::canceled, &futureWatcher, &QFutureWatcher<void>::cancel);QObject::connect(&futureWatcher, &QFutureWatcher<void>::progressRangeChanged, &dialog, &QProgressDialog::setRange);QObject::connect(&futureWatcher, &QFutureWatcher<void>::progressValueChanged, &dialog, &QProgressDialog::setValue);// Our function to computestd::function<void(int&)> spin = [](int &iteration) {const int work = 1000 * 1000 * 40;volatile int v = 0;for (int j = 0; j < work; ++j)++v;qDebug() << "iteration" << iteration << "in thread" << QThread::currentThreadId();};// Start the computation.futureWatcher.setFuture(QtConcurrent::map(vector, spin));// Display the dialog and start the event loop.dialog.exec();futureWatcher.waitForFinished();// Query the future to check if was canceled.qDebug() << "Canceled?" << futureWatcher.future().isCanceled(); }解析下:
這里設置了20個資源。
?①關聯完成;
②關聯退出;
③將QFutureWatcher的范圍設置到QProcessDialog中;
④將QFutureWatcher的當前進度值設置到QProcessDialog中。
這里創建了一個工作函數:
?傳入一個資源(對應的是iteration),然后里面就是去熬時間的代碼。
下面就是開始任務的函數:
?先看下這個函數,也就是啟動函數:
?每一個sequence都會調用一次function。這個sequence的每一項以引用的方式傳給這個函數,每一次調用函數都會對sequence里面的項進行修改。
再看下這個函數:
?設置監聽,監聽QFuture,上面的Qt::Concurrent就是會返回QFuture。然后會發出上面那4個信號。
總結
以上是生活随笔為你收集整理的Qt文档阅读笔记-QtConcurrent Progress Dialog Example解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-QThreadPool
- 下一篇: Qt文档阅读笔记-QWebEngineV