2016-09-22 75 views
0

我面临着一个奇怪的问题,而试图执行以下程序QT信号插槽不工作

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; 
    }; 

当我尝试执行程序时,插槽没有被调用? 如果我把moveToThraed(),那么代码将工作,但不会为我的puprose服务。我错过了什么?

回答

8

您未启动主事件循环。

您的主要功能应该是这个样子:

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

Qt的排队连接,如果在接收线程中运行任何事件循环无法正常工作。

当接收者对象居住在发出信号的线程以外的线程中时,Qt::AutoConnection使用Qt::QueuedConnection,请参见docs

A Qt::QueuedConnection通过将事件发布到目标线程的事件循环(接收者QObject所在的线程)来工作。当该事件被处理时(通过事件循环),在目标线程中调用对该槽的调用。

在你的情况下,主线程总是停留在:

while(1) 
    sleep(1); 

所以,它永远无法执行任何东西。

+0

我没有得到你。 – Griffin

+0

你救了我一天 – Griffin

+0

exec是否在主线程中运行? – Griffin

0

像@Mike说的,你需要启动QT的主事件循环。 Qt应用程序都会有这个在其主:

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

你的情况:

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