Search code examples
c++multithreadingqtsignals-slotsqt4.8

Signal is not calling slot from another thread


I am trying to update gui from another thread by using this: https://stackoverflow.com/a/14546167/2236297

This is my workerthread:

class WorkerThread : public QThread {
    void run() {
        while(1) {

            //QTcpSocket messenger;
            //messenger.connectToHost("192.168.1.20", 61000);
            //if(!messenger.waitForConnected(3000))
            //{
                emit progressChanged("111");
            //}
        }
    }
    // Define signal:
    signals:
    void progressChanged(QString q)
    {

    }
};

Only difference is I declared this class as a inner class and defined progressChanged. In his example signal was just declared, not defined.

My onProgressChanged:

void ApplicationController::onProgressChanged(QString info) 
{
    // Processing code
    ui.label_2->setText("Latest info: " + info);
}

This is how I start thread in my constructor:

ApplicationController::ApplicationController(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

     WorkerThread *workerThread = new WorkerThread;
    // Connect our signal and slot
    connect(workerThread, SIGNAL(progressChanged(QString)),
                          SLOT(onProgressChanged(QString)));
    // Setup callback for cleanup when it finishes
     connect(workerThread, SIGNAL(finished()),
             workerThread, SLOT(deleteLater()));
    // Run, Forest, run!
    workerThread->start(); // This invokes WorkerThread::run in a new thread

}

Question is: why my slot isn't called. What should I change?

EDIT

Changed workerthread.

.h file

class WorkerThread : public QThread
    {
        Q_OBJECT

    public:
        WorkerThread();
        ~WorkerThread();
        void run();

    private:

    signals:
        void progressChanged(QString info);
    };

.cpp file

WorkerThread::WorkerThread() { }
WorkerThread::~WorkerThread() { }

void WorkerThread::run()
{
    while(1) {
        QTcpSocket messenger;
        messenger.connectToHost("192.168.1.20", 61000);
        if(!messenger.waitForConnected(3000))
        {
            emit progressChanged((QString("%1").arg(messenger.error())));
        }
    }
}

In debug, emit works. But slot is not called in main function.


Solution

  • SOLVED

    There are multiple errors:

    • First of all workerThread should be defined as seperate class not an inner class.

    • Slot should be declared under slots:

      public slots: void onProgressChanged(QString info);