Griffin Griffin - 2 months ago 17
C++ Question

QT signal slot is not working

I am facing a strange problem while trying to execute the following program

main.cpp


#include "sample.h"
#include <QList>
#include <unistd.h>

int main(int argc, char **argv)
{
A a;
a.callA();
while(1)
sleep(1);
return 0;
}


sample.cpp

#include "sample.h"
#include <QList>
#include <QMetaMethod>
#include <unistd.h>


Thread::Thread(A *a)
{
}
void Thread::run()
{
int i = 5;
while (i){
qDebug()<< i;
sleep(2);
i--;
}
emit processingDone(">>> FROM THREAD");
qDebug()<<"Emited signal from thread";
}

void A::callA()
{
qDebug()<<"from callA";
//moveToThread(thread);
thread->start();
//thread->run();
//emit signalA(">>> FROM CallA");
}

void A::slotA(QString arg)
{
qDebug()<<"from sloatA "<< arg;
}


sample.h


class A;
class Thread : public QThread
{
Q_OBJECT
public:
Thread(A *a);
~Thread(){
qDebug()<<"Thread is destroyed";
}
void run();
signals:
void processingDone(QString arg);
};

class A : public QObject{
Q_OBJECT

public:
A(){
qDebug()<<"Registering";
thread = new Thread(this);
connect(thread, SIGNAL(processingDone(QString)), this, SLOT(slotA(QString)));
connect(this,SIGNAL(signalA(QString)), this, SLOT(slotA(QString)));
}
public slots:
void callA();
void slotA(QString arg);

signals:
void signalA(QString arg);

private:
Thread *thread;
};


When I try to executed the program, the slot is not getting invoked?
if I put moveToThraed(), then the code will work but that won't serve my puprose. Is anything i am missing?

Answer

You are not starting a main event loop.

your main function should look something like this:

QApplication app(argc, argv);
A a;
a.callA();
return app.exec();

Qt queued connections can't work if there is no event loop running in the receiving thread.

When the receiver object lives in a thread other than the thread where the signal is emitted, Qt::AutoConnection uses a Qt::QueuedConnection, see docs.

A Qt::QueuedConnection works by posting an event to the event loop of the target thread (the thread where the receiver QObject lives). When that event is processed (by the event loop) the call to the slot is invoked in the target thread.

In your case, the main thread is always stuck in:

while(1)
    sleep(1);

So, it will never be able to execute anything else.