I am attempting to connect a signal from a QObject to a functor as defined in the QT5 documentation:
http://doc.qt.io/qt-5/qobject.html#connect-5
Relevant code:
namespace someNamespace
{
void processFinished()
{
qDebug() << "A Thread has finished processing!!!";
}
void executeWorkerOnSeparateTread()
{
QThread* thread = new QThread;
Worker* worker = new Worker();
worker->moveToThread(thread);
QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
QObject::connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
QObject::connect(thread, SIGNAL(started()), worker, SLOT(process()));
QObject::connect(worker, SIGNAL(finished()), processFinished); //DOES NOT COMPILE
thread->start();
}
}
If I were to comment out just the line that does not compile, this code compiles and executes with no problems. I just can't get that connection to compile.
Compiler Error:
no matching function for call to 'QObject::connect(Worker*&, const char*, void(&)())'
of course Worker inherits QObject and has the Q_OBJECT keyword in it. the fact that this works without the problematic line also eliminates other lines being the problem.
Any ideas as to what I'm doing wrong?? It seems to me like it should be this straightforward.
If relevant, QT version is 5.8 and GCC version is 4.8.5.
Thanks!!
That's correct, there is no way to connect to a function in a namespace or a lambda using the moc
-based signals and slots. Have a look at the list of overloads for QObject::connect()` to see why the error is reported the way it is. The correct function to use here is connect overload for a functor and it uses a pointer to a member function as its first argument:
QMetaObject::Connection
QObject::connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
Thus, use:
QObject::connect(worker, &Worker::finished, processFinished);
Note the lack of round braces after function names - being careless with that caused me some headache back in the days.
That also means you may want to switch to the new syntax for uniformity sake.
Refer to part 1 and part 2 of the blog post series by Olivier Goffart, the author of the new signal and slot syntax, for more details. Also see a detailed side-by-side rundown of the two approaches here.