jsaji
jsaji

Reputation: 920

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?

Upvotes: 0

Views: 1508

Answers (2)

Mike
Mike

Reputation: 8355

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.

Upvotes: 8

RvdK
RvdK

Reputation: 19790

Like @Mike says, you need to start the main event loop of QT. Every QT application has this in their main:

QApplication a(argc, argv);
return a.exec();

In your case:

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    A a;
    a.callA();
    return app.exec();
}

Upvotes: 0

Related Questions