Detailed explanation of signal and slot usage of QThread

The signal and slot usage of QThread mainly involves the following aspects:

The finished() signal of QThread

When the QThread finishes executing, the finished() signal is sent. We can perform some operations after the QThread is executed by connecting the signal to the slot function.

For example:

class MyThread : public QThread
{
    Q_OBJECT

public:
    void run() override
    {
        // 执行一些操作...
        emit finished(); // 发出finished()信号
    }
};

MyThread thread;
connect(&thread, &MyThread::finished, [=](){
   qDebug() << "thread finished";
});

The started() signal of QThread

When the start() function of QThread is called to start the thread, the started() signal is issued. We can perform some operations before or after the thread starts by connecting the signal to the slot function.

For example:

class MyThread : public QThread
{
    Q_OBJECT

public:
    void run() override
    {
        qDebug() << "thread running...";
    }
};

MyThread thread;
connect(&thread, &MyThread::started, [=](){
   qDebug() << "thread started";
});
thread.start();

inter-thread communication

Since QThread runs code in a new thread, it cannot directly access objects in the main thread. In order to transfer data and messages between different threads, we can use the cross-thread communication mechanism provided by Qt - signals and slots.

For example, send a message to the main interface in the child thread:

class MyThread : public QThread
{
    Q_OBJECT

signals:
    void message(const QString& msg);

public:
    void run() override
    {
        emit message("Hello from thread");
    }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public slots:
    void handleMessage(const QString& msg)
    {
        qDebug() << "Received message:" << msg;
    }
};

MyThread thread;
MainWindow mainWindow;

connect(&thread, &MyThread::message, &mainWindow, &MainWindow::handleMessage);
thread.start();

In the above example, the child thread sends a message to the main thread by issuing a message signal. The main interface connects this signal to its own handleMessage slot function to receive and process messages.

Summarize:

The signal and slot usage of QThread is very flexible and can realize various functions. It should be noted that when using cross-thread communication, thread safety must be ensured.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/131141961