jocala jocala - 2 months ago 16
C++ Question

QTConcurrent doesn't compile

I have a recursive directory copy function I'd like to run in the background. The function takes two QString arguments, filepath and dir.

From .pro:

QT += core gui sql network concurrent
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
LIBS += -lQt5Concurrent


From code:

#include <QtConcurrent/QtConcurrent>
#include <qtconcurrentrun.h>
#include <QThread>
...

QFuture <void> future = QtConcurrent::run(copyFolder(filepath,dir));


I get the following compile error:

error: no matching function for call to 'run'
QFuture <void> future = QtConcurrent::run(copyFolder(filepath,dir) );
^~~~~~~~~~~~~~~~~


If I call the function like this:

QFuture <void> future = QtConcurrent::run(copyFolder, filepath,dir );

error: reference to non-static member function must be called
QFuture <void> future = QtConcurrent::run(copyFolder, filepath,dir );
^~~~~~~~~~


What am I doing wrong?

Answer

I get the following compile error:

error: no matching function for call to 'run'
QFuture <void> future = QtConcurrent::run(copyFolder(filepath,dir) );
                  ^~~~~~~~~~~~~~~~~

You shouldn't be passing arguments the way you are doing. Instead you should pass your function's argument as arguments to QtConcurrent::run, see docs here.

Your call should look something like this:

QFuture <void> future = QtConcurrent::run(copyFolder, filepath, dir);

This way QtConcurrent will copy the arguments you have passed and perform the function call in a thread from the default QThreadPool .

If I call the function like this:

QFuture <void> future = QtConcurrent::run(copyFolder, filepath,dir );
  error: reference to non-static member function must be called
QFuture <void> future = QtConcurrent::run(copyFolder, filepath,dir );
                               ^~~~~~~~~~

If you have to call a non-static member function in your class, you have to pass the object that you want to run the function on, see docs here. Assuming you are using QtConcurrent::run from another member function in your class (since you would get a different error if not), you should do something like this:

QFuture <void> future = QtConcurrent::run(this, &ClassName::copyFolder, filepath, dir);

Note that, you have to make sure that that all accesses to shared data (between both threads) should be serialized (maybe using a QMutex).