BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Qt5 Tutorial QtConcurrent QProgressDialog with QFutureWatcher - 2020





Bookmark and Share





bogotobogo.com site search:




QProgressDialog

In this tutorial, we'll learn how to use QProgressDialog with QtConcurrent. Also, we'll learn how to use the QFuture class of the QtConcurrent module to execute a long lasting operation in a separated thread and how to monitor the progress and state with the QFutureWatcher class.

We'll see how the QtConcurrent detects ideal number of threads for the system and make them work for our massive task in parallel.



I've already covered the QProgressDialog in my tutorial: QProgress Dialog - Modal and Modeless.

But there are some methods (actually slots) of QProgressDialog class we haven't used, and some of them will appear in this tutorial.

They are:

  1. void reset()
    Resets the progress dialog. The progress dialog becomes hidden if autoClose() is true.
  2. void setLabelText(const QString & text)
  3. void setRange(int minimum, int maximum)
    Sets the progress dialog's minimum and maximum values to minimum and maximum, respectively.
    If maximum is smaller than minimum, minimum becomes the only legal value.
    If the current value falls outside the new range, the progress dialog is reset with reset().




QtConcurrent

When we do multi-threading coding, thanks to QtConcurrent, we may not necessarily deal with low-level threading primitives such as mutexes, read-write locks, wait conditions, or semaphores. Instead, we just write our code using high-level APIs that QtConcurrent.

Among those APIs, we should know QtConcurrent::map() since it will be used in this tutorial. What it does is it applies a function to every item in a container, modifying the items in-place. For example:

QtConcurrent::map(vector, function)
So, to every item in the vector, the function will be applied.





QFuture and QFutureWatcher


QFuture

QFuture class represents the result of an asynchronous computation. We've already used this to get the return value from QtConcurrent::run() in our previous tutorial (a href="http://www.bogotobogo.com/Qt/Qt5_QtConcurrent_RunFunction_QThread.php" target="_blank">Creating QThreads using QtConcurrent):

QFuture t1 = QtConcurrent::run(myRunFunction, QString("A"));


QFutureWatcher

The QFutureWatcher class allows us to monitor a QFuture using signals and slots.

QFutureWatcher provides information and notifications about a QFuture. Use the setFuture() function to start watching a particular QFuture. The future() function returns the future set with setFuture().

In our example, the following signal will be used:

  1. void canceled()
  2. void finished()
  3. void progressRangeChanged(int minimum, int maximum)
  4. void progressValueChanged(int progressValue)

Also in this tutorial, we'll use:

 void QFutureWatcher::setFuture(const QFuture & future)
function. This starts watching the given future. One of the signals might be emitted for the current state of the future. For example, if the future is already stopped, the finished signal will be emitted. To avoid a race condition, it is important to call this function after doing the connections as we do in this tutorial:
QObject::connect
...
futureWatcher.setFuture(QtConcurrent::map(vector, spin));




Run

Let's run the code:

TaskDialog.png

The UI of this sample application consists of two buttons, one to start the time consuming work and one to cancel the launcher itself. We get the maximum iteration from the spinBox.

Progress_80.png

The progress of the operation is visualized by a progress bar. We can cancel the task at any time. Above the cancel is a label that shows the number of CPU cores that are used for the calculation.

iteration 0 in thread 0x1d64 
iteration 1 in thread 0x7b8 
iteration 2 in thread 0x1d64 
iteration 3 in thread 0x7b8 
iteration 4 in thread 0x1d64 
iteration 5 in thread 0x7b8 
iteration 6 in thread 0x1d64 
iteration 8 in thread 0x1d64 
iteration 7 in thread 0x7b8 
iteration 9 in thread 0x1d64 
Canceled? false 




Code Review

The ProgressDialog is the core class in this tutorial that contains all the business logic.

It provides the two slots to start and cancel the calculation and properties that reflect the state and progress of the calculation. ProgressDialog contains a QFutureWatcher as member variable, which is used to monitor the progress and state of a QFuture instance. For this the signals of the future watcher are connected against private slots inside the constructor of ProgressDialog.

void TaskDialog::on_doTaskButton_clicked()
{
    // get the number of iterations
    int iterations = ui->spinBoxIterations->text().toInt();
    
    // 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.
    // Monitor progress changes of the future
    QFutureWatcher<void> futureWatcher;
    QObject::connect(&futureWatcher;, SIGNAL(finished()), &dialog;, SLOT(reset()));
    QObject::connect(&dialog;, SIGNAL(canceled()), &futureWatcher;, SLOT(cancel()));
    QObject::connect(&futureWatcher;, SIGNAL(progressRangeChanged(int,int)), &dialog;, SLOT(setRange(int,int)));
    QObject::connect(&futureWatcher;, SIGNAL(progressValueChanged(int)), &dialog;, SLOT(setValue(int)));

    // 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();
}

When we hit "Do Task" button on the TaskDialog, the on_doTaskButton_clicked() slot is invoked.
After getting the number of iterations

int iterations = ui->spinBoxIterations->text().toInt();

a vector is filled with some dummy value that act as input values for the task.

// Prepare the vector.
QVector<int> vector;
for (int i = 0; i < iterations; ++i)
    vector.append(i);
Then the actual calculation is started by calling QtConcurrent::map().

// Start the computation.
futureWatcher.setFuture(QtConcurrent::map(vector, spin));
This method from the QtConcurrent module takes a container and a function as parameters and executes the function once for each entry in the container in a separated thread. The function spin() we use in this example just burns some CPU cycles:

void 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();
}

Note that the call to QtConcurrent::map() does not block until the task has finished but returns a QFuture object instead, which acts as a handle to monitor the progress and state of the task.

We set the returned future on the future watcher member variable and now the future watcher will emit the appropriated signals as soon as the future changes its progress or state.

When the user wants to cancel the calculation and clicks on the 'Cancel' button, then the canceled() signal is invoked, which calls cancel() on the QFutureWatcher object. This will cause the running task (and the used threads) to terminate.

QObject::connect(&dialog;, SIGNAL(canceled()), &futureWatcher;, SLOT(cancel()));

Internally the QtConcurrent module uses the QThreadPool class for distributing the calculation over multiple threads. The thread pool uses as many threads in parallel as returned by QThread::idealThreadCount(), which by default is the number of cores of the device the application is running on.

QProgressDialog dialog;
dialog.setLabelText(QString("Progressing using %1 thread(s)...").arg(QThread::idealThreadCount()));




Source Code

SourceList.png

  1. taskdialog.cpp
  2. taskdialog.h
  3. taskdialog.ui
  4. main.cpp
  5. QtConcurrentQProgressDialog.pro






Qt 5 Tutorial

  1. Hello World
  2. Signals and Slots
  3. Q_OBJECT Macro
  4. MainWindow and Action
  5. MainWindow and ImageViewer using Designer A
  6. MainWindow and ImageViewer using Designer B
  7. Layouts
  8. Layouts without Designer
  9. Grid Layouts
  10. Splitter
  11. QDir
  12. QFile (Basic)
  13. Resource Files (.qrc)
  14. QComboBox
  15. QListWidget
  16. QTreeWidget
  17. QAction and Icon Resources
  18. QStatusBar
  19. QMessageBox
  20. QTimer
  21. QList
  22. QListIterator
  23. QMutableListIterator
  24. QLinkedList
  25. QMap
  26. QHash
  27. QStringList
  28. QTextStream
  29. QMimeType and QMimeDatabase
  30. QFile (Serialization I)
  31. QFile (Serialization II - Class)
  32. Tool Tips in HTML Style and with Resource Images
  33. QPainter
  34. QBrush and QRect
  35. QPainterPath and QPolygon
  36. QPen and Cap Style
  37. QBrush and QGradient
  38. QPainter and Transformations
  39. QGraphicsView and QGraphicsScene
  40. Customizing Items by inheriting QGraphicsItem
  41. QGraphicsView Animation
  42. FFmpeg Converter using QProcess
  43. QProgress Dialog - Modal and Modeless
  44. QVariant and QMetaType
  45. QtXML - Writing to a file
  46. QtXML - QtXML DOM Reading
  47. QThreads - Introduction
  48. QThreads - Creating Threads
  49. Creating QThreads using QtConcurrent
  50. QThreads - Priority
  51. QThreads - QMutex
  52. QThreads - GuiThread
  53. QtConcurrent QProgressDialog with QFutureWatcher
  54. QSemaphores - Producer and Consumer
  55. QThreads - wait()
  56. MVC - ModelView with QListView and QStringListModel
  57. MVC - ModelView with QTreeView and QDirModel
  58. MVC - ModelView with QTreeView and QFileSystemModel
  59. MVC - ModelView with QTableView and QItemDelegate
  60. QHttp - Downloading Files
  61. QNetworkAccessManager and QNetworkRequest - Downloading Files
  62. Qt's Network Download Example - Reconstructed
  63. QNetworkAccessManager - Downloading Files with UI and QProgressDialog
  64. QUdpSocket
  65. QTcpSocket
  66. QTcpSocket with Signals and Slots
  67. QTcpServer - Client and Server
  68. QTcpServer - Loopback Dialog
  69. QTcpServer - Client and Server using MultiThreading
  70. QTcpServer - Client and Server using QThreadPool
  71. Asynchronous QTcpServer - Client and Server using QThreadPool
  72. Qt Quick2 QML Animation - A
  73. Qt Quick2 QML Animation - B
  74. Short note on Ubuntu Install
  75. OpenGL with QT5
  76. Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
  77. Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
  78. Video Player with HTML5 QWebView and FFmpeg Converter
  79. Qt5 Add-in and Visual Studio 2012
  80. Qt5.3 Installation on Ubuntu 14.04
  81. Qt5.5 Installation on Ubuntu 14.04
  82. Short note on deploying to Windows







Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Qt 5 Tutorial



Hello World

Signals and Slots

Q_OBJECT Macro

MainWindow and Action

MainWindow and ImageViewer using Designer A

MainWindow and ImageViewer using Designer B

Layouts

Layouts without Designer

Grid Layouts

Splitter

QDir

QFile (Basic)

Resource Files (.qrc)

QComboBox

QListWidget

QTreeWidget

QAction and Icon Resources

QStatusBar

QMessageBox

QTimer

QList

QListIterator

QMutableListIterator

QLinkedList

QMap

QHash

QStringList

QTextStream

QMimeType and QMimeDatabase

QFile (Serialization I)

QFile (Serialization II - Class)

Tool Tips in HTML Style and with Resource Images

QPainter

QBrush and QRect

QPainterPath and QPolygon

QPen and Cap Style

QBrush and QGradient

QPainter and Transformations

QGraphicsView and QGraphicsScene

Customizing Items by inheriting QGraphicsItem

QGraphicsView Animation

FFmpeg Converter using QProcess

QProgress Dialog - Modal and Modeless

QVariant and QMetaType

QtXML - Writing to a file

QtXML - QtXML DOM Reading

QThreads - Introduction

QThreads - Creating Threads

Creating QThreads using QtConcurrent

QThreads - Priority

QThreads - QMutex

QThreads - GuiThread

QtConcurrent QProgressDialog with QFutureWatcher

QSemaphores - Producer and Consumer

QThreads - wait()

MVC - ModelView with QListView and QStringListModel

MVC - ModelView with QTreeView and QDirModel

MVC - ModelView with QTreeView and QFileSystemModel

MVC - ModelView with QTableView and QItemDelegate

QHttp - Downloading Files

QNetworkAccessManager and QNetworkRequest - Downloading Files

Qt's Network Download Example - Reconstructed

QNetworkAccessManager - Downloading Files with UI and QProgressDialog

QUdpSocket

QTcpSocket

QTcpSocket with Signals and Slots

QTcpServer - Client and Server

QTcpServer - Loopback Dialog

QTcpServer - Client and Server using MultiThreading

QTcpServer - Client and Server using QThreadPool

Asynchronous QTcpServer - Client and Server using QThreadPool

Qt Quick2 QML Animation - A

Qt Quick2 QML Animation - B

Short note on Ubuntu Install

OpenGL with QT5

Qt5 Webkit : Web Browser with QtCreator using QWebView Part A

Qt5 Webkit : Web Browser with QtCreator using QWebView Part B

Video Player with HTML5 QWebView and FFmpeg Converter

Qt5 Add-in and Visual Studio 2012

Qt5.3 Installation on Ubuntu 14.04

Qt5.5 Installation on Ubuntu 14.04

Short note on deploying to Windows




Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong













Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master