Search code examples
c++qtqtconcurrent

is it possible to use QtConcurrent::run() with a function member of a class


I can't seem to be able to associate QtConcurrent::run() with a method (function member of a class) only with a simple function. How can I do this?

With a regular function I cannot emit signals and its a drag. Why would anyone find this a better alternative to QThread is beyond me and would like some input.


Solution

  • Yes, this is possible (and quite easy).

    Here is an example (from the Qt documentation):

    // call 'QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const' in a separate thread
    QString string = ...;
    QFuture<QStringList> future = QtConcurrent::run(string, &QString::split, QString(", "), QString::KeepEmptyParts, Qt::CaseSensitive);
    ...
    QStringList result = future.result();
    

    Basically, all you have to do is pass a pointer to the object as the first argument and the address of the method as the second argument (followed by any other arguments).

    See: https://doc.qt.io/qt-5/qtconcurrentrun.html