Question

I'm writing a Qt Application in C++. I have a QRunnable running in a QThreadPool, and it sends a signal to the main thread. The problem is, the connection doesn't work: the signal is never received by the main thread, even though I've verified that the code doing the emit is indeed called. Here is my code:

My QRunnable class:

class OfflineAnalysisThread : public QObject, public QRunnable
{
Q_OBJECT

public:
void run();
void sendMessage(QString &qmsg)
{
    emit threadMessageCallback(qmsg);
}

signals:
void threadMessageCallback(QString &string);
};

And the calling class (main thread):

class OfflineAnalysisMain : public QObject
{
Q_OBJECT

public:

    (...)

public slots:
void threadMsg(QString &string);
};

The code that instantiates the new QRunnables and starts them:

void OfflineAnalysisMain::myFunction()
{
    OfflineAnalysisThread *newTask = new OfflineAnalysisThread();

    QObject::connect(newTask, SIGNAL(threadMessageCallback(QString &)), this, SLOT(threadMsg(QString &)));

    QThreadPool::globalInstance()->start(newTask);
}

So, from my QRunnable's run function, I call sendMessage and then I do QApplication::exec(). I have a breakpoint on the threadMsg slot implementation in OfflineAnalysisMain.cpp, and that function is never called.

What am I doing wrong?

UPDATE:

Definition of my OfflineAnalysisThread::run() function:

void OfflineAnalysisThread::run()
{
    std::string myMsg("This is my message");
    sendMessage(myMsg);

    QApplication::exec();
}

I have also tried without the QApplication::exec();, without success.

Was it helpful?

Solution

Remove the call to QApplication::exec() from within run(). This is ideally called from within your main function.

In order to get your code to work, I had to write the following main function:

#include <QApplication>
#include <QMetaType>

#include <offlineanalysismain.h>

int main(int argc, char* argv[])
{
   QApplication app(argc, argv);

   qRegisterMetaType<QString>("QString&");

   OfflineAnalysisMain* main = new OfflineAnalysisMain;
   main->myFunction();

   return app.exec();
}

Note the call to qRegisterMetaType, which allows Qt to pass a QString through a signal-slot connection that cross thread boundaries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top