3

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.

Karl Arsenault
  • 147
  • 1
  • 1
  • 9
  • Show us your definition of `OfflineAnalysisThread::run()`. From what you've written, it doesn't sound right. You shouldn't be calling `QApplication::exec()` from within `run()`. – RA. Mar 02 '13 at 20:45
  • I just updated my post with my definition of run(). Please take a look. Also I've tried without the exec() as well (in fact that was my original code, I added exec() to see if that would work). – Karl Arsenault Mar 02 '13 at 21:30

1 Answers1

1

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.

RA.
  • 7,542
  • 1
  • 34
  • 35