Qt Thread Data Transfer: Signals & Slots

In Qt, you can use the signal and slot mechanism to transfer data between threads. Here are the specific steps:

  1. Define a signal in the thread class to send data.
  2. Connect this signal to a slot function in the main thread to receive data.
  3. Emit this signal in the thread to pass data to the main thread.

Here is a simple example:

#include <QThread>
#include <QObject>

class MyThread : public QThread
{
    Q_OBJECT
signals:
    void dataReady(int value);

protected:
    void run() override
    {
        int result = 42;
        emit dataReady(result);
    }
};

class MyObject : public QObject
{
    Q_OBJECT
public slots:
    void onDataReady(int value)
    {
        qDebug() << "Data received from thread: " << value;
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyThread thread;
    MyObject obj;

    QObject::connect(&thread, &MyThread::dataReady, &obj, &MyObject::onDataReady);

    thread.start();

    return app.exec();
}

In the example above, the MyThread class inherits from QThread and defines a dataReady signal for sending data. The MyObject class inherits from QObject and defines a slot function onDataReady for receiving data.

In the main function, a thread object and an object are created and the thread’s dataReady signal is connected to the object’s onDataReady slot function. When the thread runs, it emits the dataReady signal, passing the data to the slot function onDataReady in the main thread, thereby achieving the functionality of data being passed out from the thread.

bannerAds