@qwe3 said in How to stop QThread?:
I change a little your code ( I never before used QFuture etc. so maybe I do something wrong ):
runnable->run(); after futureWatcherProgress.setFuture(runnable->getFuture());
Okay, my code was o a little bit too rough, so I will be more explicit:
a create a class based on QRunnable to be able to use it with QThreadPool.
in the method getFuture(), the class instance is transformed to future a will run in next thread available the thread pool. So the run() method will be called a soon as possible
after that I record the QFuture instance returned into the QFutureWatcher instance to be aware about state changes.
Your fun1() don't made sense; the QFutureWatcher is a local variable which will be delete at function end!
Change it like this:
void MainWindow::fun1()
{
// do NOT use a local variable!!!
auto futureWatcherProgress = new QFutureWatcher<void>();
// ==> delete QFuteWatcher instance instance when process done
connect(futureWatcherProgress, &QFutureWatcher<void>::finished, futureWatcherProgress, [futureWatcherProgress]() {
futureWatcherProgress->deleteLater();
qDebug() << "Processing done.";
});
// ==> stop future on application exit
connect(qApp, &QCoreApplication::aboutToQuit, futureWatcherProgress, &QFutureWatcher<void>::cancel);
// follow progression
connect(futureWatcherProgress, &QFutureWatcher<void>::progressValueChanged, this, [](int progressValue){
qDebug() << "Progression is" << progressValue;
});
connect(futureWatcherProgress, &QFutureWatcher<void>::progressRangeChanged, this, [](int minimum, int maximum){
qDebug()<< "Progression range from" << minimum << "to" << maximum;
});
connect(&futureWatcherProgress, &QFutureWatcher<void>::progressTextChanged, qApp, [](const QString &progressText) {
qDebug() << "Progression:" << progressText;
});
// create worker ==> QRunnable are automatically destroyed when finished (cf QRunnable::autoDelete())
auto runnable = new Work();
// register future and start processing
futureWatcherProgress->setFuture(runnable->getFuture());
}