#include <QApplication>#include <QFuture>#include <QFutureWatcher>#include <QProgressDialog>#include "runextensions.h"//heavy work :)static void doWork(QFutureInterface<void> &future){ future.setProgressRange(0, 100); static const int iterations = 10*1000*1000; for (int i = 0; i < iterations; i++) { if (future.isCanceled()) break; future.setProgressValue(100.0*i/iterations); QObject *object = new QObject; object->setObjectName("Object"); delete object; }}int main(int argc, char *argv[]){ QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); QProgressDialog progress; progress.setWindowTitle(QObject::tr("Work")); progress.setLabelText(QObject::tr("Working...")); progress.setRange(0, 100); QFutureWatcher<void> watcher; QObject::connect(&watcher, SIGNAL(finished()), &app, SLOT(quit())); QObject::connect(&watcher, SIGNAL(progressValueChanged(int)), &progress, SLOT(setValue(int))); QObject::connect(&progress, SIGNAL(canceled()), &watcher, SLOT(cancel())); QFuture<void> future = QtConcurrent::run(&doWork); watcher.setFuture(future); progress.show(); return app.exec();}
QFuture<void> backgroundJob = QtConcurrent::run(report, &XMLReport::Export);
void XMLReport::Export(QFutureInterface<void> &future)
C++ (Qt)#include <QApplication> #include <QFuture>#include <QFutureWatcher>#include <QProgressDialog> #include "runextensions.h" class Work{ //heavy work :)public: void doWork(QFutureInterface<void> &future) { future.setProgressRange(0, 100); static const int iterations = 10*1000*1000; for (int i = 0; i < iterations; i++) { if (future.isCanceled()) break; future.setProgressValue(100.0*i/iterations); QObject *object = new QObject; object->setObjectName("Object"); delete object; } }}; int main(int argc, char *argv[]){ QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); QProgressDialog progress; progress.setWindowTitle(QObject::tr("Work")); progress.setLabelText(QObject::tr("Working...")); progress.setRange(0, 100); QFutureWatcher<void> watcher; QObject::connect(&watcher, SIGNAL(finished()), &app, SLOT(quit())); QObject::connect(&watcher, SIGNAL(progressValueChanged(int)), &progress, SLOT(setValue(int))); QObject::connect(&progress, SIGNAL(canceled()), &watcher, SLOT(cancel())); Work work; QFuture<void> future = QtConcurrent::run(work, &Work::doWork); watcher.setFuture(future); progress.show(); return app.exec();}
QtConcurrent::run(&Work::doWork, &work);