PDA

View Full Version : signals are not working from QThread derived class



dpn
15th September 2013, 16:36
Hi all,

Application couldn't receive signal from QThread object.

I have implemented this way:

workerthread.h:
----------------------

#ifndef WORKERTHREAD_H
#define WORKERTHREAD_H

#include <QThread>

class workerthread : public QThread
{
Q_OBJECT
public:
explicit workerthread(QObject *parent = 0);
void run();

signals:
void signal_worker_thread();
};

#endif // WORKERTHREAD_H

workerthread.cpp
-------------------------

#include "workerthread.h"
#include <QDebug>

workerthread::workerthread(QObject *parent) :
QThread(parent)
{
}

void workerthread::run()
{
for(int i = 0; i < 10; ++ i)
{
qDebug() << "workerthread::signal_worker_thread()";
emit signal_worker_thread();
}
return;
}

WorkerThread is derived from QThread and overridden Run() method.
I have launched this thread on GUI - button click event to do background process.

Button click slot event:
---------------------------------

void ProductNameDialog::slotButtonClicked()//
{
workerthread *pthread = new workerthread();
QObject::connect(pthread, SIGNAL(signal_worker_thread()), this, SLOT(slotTest()));

pthread->start();
pthread->wait();

accept();
return;
}


I have tested with sample Qt-GUI MainWindow application. It's working fine.

When I integrated into my application, slotTest() is not fired. I hope, I am missing something. Can somebody suggest me what I am missing here.

Thanks in advance.

anda_skoa
15th September 2013, 22:18
the problem is that you call QThread::wait()
That will block the caller thread, in your case your GUI thread. While it is blocked it can't do anything, so it cannot process the signal event it is getting.

Potential solution (depending in your problem)
do not call wait, connect thread's finished() signal to dialog's accept() slot before calling thread's start method.

Cheers,
_

high_flyer
16th September 2013, 10:57
in addition to what anda_skoa said, having the calling thread wait for your thread to end by blocking it, makes having the thread redundant.