useage of QfutureWatcher in lambda function
-
Hi
I create qt connection like below
QObject::connect(&my_class, &my_class::signal, [=](bool result, QString string) { // do something... QFutureWatcher<QByteArray>* futureWatcher = new QFutureWatcher<QByteArray>(); QObject::connect(futureWatcher, &QFutureWatcher<QByteArray>::finished, &my_class, &my_class::slot); _watcher_list.push_back(futureWatcher); QFuture<QByteArray> future = QtConcurrent::run(static_function); futureWatcher->setFuture(future); } // do something... );
After finish work static_function, finished signal not emitted.
Did I use it wrong?
-
@Mintogo said in useage of QfutureWatcher in lambda function:
QFuture<QByteArray> future = QtConcurrent::run(static_function); futureWatcher->setFuture(future); }
I'm not an expert (never done this stuff), but
future
is a local variable in the lambda body which goes out of scope and is destroyed immediately after thesetFuture(future)
statement, which doesn't sound right to me...?P.S.
Just found effectively the same question with the same answer as I have given at https://stackoverflow.com/a/43458370/489865. -
@Mintogo said in useage of QfutureWatcher in lambda function:
After finish work static_function, finished signal not emitted.
Did I use it wrong?What are you doing during "do something"?
I hope there is no forever loop there. This would lock the event loop and signal could not be done.By the way, I would change to code to this:
QObject::connect(&my_class, &MyClassName::signal, // capture "my_class" per reference and NOT as copy!! [=, &my_class](bool result, QString string) { // do something... QFutureWatcher<QByteArray>* futureWatcher = new QFutureWatcher<QByteArray>(); QObject::connect(futureWatcher, &QFutureWatcher<QByteArray>::finished, &my_class, // capture "my_class" per reference and NOT as copy!! [&my_class, futureWatcher]() { my_class->slot(futureWatcher->result()); futureWatcher->deleteLater(); // free memory } ); futureWatcher->setFuture(QtConcurrent::run(static_function)); } // do something... );