Qt文档阅读笔记-QtConcurrent Progress Dialog Example解析

x33g5p2x  于2021-11-10 转载在 其他  
字(2.1k)|赞(0)|评价(0)|浏览(386)

这篇展示了如何监听任务的进度。

QtConcurrent Progress Dialog使用QFutrueWathcer类去监听任务进程进展。

代码如下:

progressdialog.pro

QT += concurrent widgets
CONFIG += console

SOURCES += main.cpp

target.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/progressdialog
INSTALLS += target

main.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 compute
    std::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个信号。

相关文章