SoFunction
Updated on 2025-03-02

Introduction to the use of QT thread QThread

1. Overview

There are two ways to use QThread

  1. QObject::moveToThread()
  2. DerivedQThreadSubclasses of

2. moveThread example

Step Overview:

  • Define aQObjectDerived class, defines a slot function in the derived class, which is used to perform specific work
  • In the class to use the thread, create a new oneQThreadandQObjectDerived class objects and usemoveThread()Leave the processing of derived classes toQThread
  • Connect the signal that triggers the thread's work with the slot function of the derived class

The code is as follows:

#ifndef THREADWORKER_HPP
#define THREADWORKER_HPP
#include <QObject>
#include <QString>
#include <QThread>
#include <QDebug>
class ThreadWorker:public QObject
{
    Q_OBJECT
public:
    ThreadWorker() {}
public slots:
    void work(QString p1)
    {
        qDebug() << "current thread ID:" << QThread::currentThreadId();
        qDebug() << p1;
        QThread::sleep(10);
        qDebug() << "thread run finish!";
    }
};
#endif // THREADWORKER_HPP

The code is as follows:

#ifndef THREADCONTROLLER_H
#define THREADCONTROLLER_H
#include ""
class ThreadController:public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    ThreadController():QObject()
    {
        ThreadWorker* threadWork = new ThreadWorker();
        // Hand over threadWork to workerThread        threadWork-&gt;moveToThread(&amp;workerThread);
        QObject::connect(this,SIGNAL(touchWork(QString)),threadWork,SLOT(work(QString)));
        QObject::connect(&amp;workerThread,&amp;QThread::finished,threadWork,&amp;QObject::deleteLater);
        ();                //Start the thread        qDebug()&lt;&lt;"current thread ID:"&lt;&lt;QThread::currentThreadId()&lt;&lt;'\n';
        emit touchWork("working");
    }
    ~ThreadController()
    {
        ();
        ();
    }
signals:
    // Send a signal to trigger the thread    void touchWork(QString p1);
};
#endif // THREADCONTROLLER_H

The code is as follows:

#include <QCoreApplication>
#include ""
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ThreadController tc = ThreadController();
    return ();
}

Notice:

Can't be any morecppUse in the fileQTThe characteristic mechanism of the signal slot is likemocNot herecppThese mechanisms are processed in files. It can be changed, but it is quite troublesome. It is recommended to define the class in the header file.

3. QThread example

Method Overview:

  • Define aQThreadderived classes and overloadrun()Function, inrun()Write specific thread code into the function
  • passstart()Start the thread

The code is as follows

#ifndef CUSTOMTHREAD_H
#define CUSTOMTHREAD_H
#include <QThread>
#include <QDebug>
class CustomThread:public QThread
{
    Q_OBJECT
public:
    CustomThread() {}
signals:
    void customThreadSignal();
public slots:
    void customThreadSlot()
    {
        qDebug()<<"current thread ID(in slot function):"<<QThread::currentThreadId()<<'\n';
    }
protected:
    void run() override
    {
        qDebug()<<"current thread ID:"<<QThread::currentThreadId()<<'\n';
        QThread::sleep(10);
        qDebug() << "thread run finish!";
        emit customThreadSignal();
    }
};
#endif // CUSTOMTHREAD_H

The code is as follows

#include <QCoreApplication>
#include ""
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug() << "main thread ID:" << QThread::currentThreadId();
    CustomThread customThread;
    QObject::connect(&customThread,&CustomThread::customThreadSignal,&customThread,&CustomThread::customThreadSlot);
    ();
    return ();
}

Output result:

main thread ID: 0x6508
current thread ID: 0x6544 

thread run finish!
current thread ID(in slot function): 0x6508 

4. Summary

  1. moveToThread

In this way, it is necessary to encapsulate all the work that needs to be performed in a class, define each task as a slot function, and associate it with the corresponding signal, and finally call itmoveToThreadSend such aQThreadObject.QThreadCallstart()Start, and then each task is triggered by the corresponding signal and then executed.

  1. QThread

This method requires that it is based onQThreadDerivation, perform derivative classesrun()Functionaloverride. Called laterstart()After that, it will runrun()function. However, the slot functions defined in the derived class are not executed by the derived class itself, but by the owner of the thread.

QThreadonlyrunFunctions are executed in a new thread, and all other functions areQThreadExecute in the generated thread

It is the most recommended officialmoveToThreadThe way, but it depends on the respective usage scenarios! ! ! For example, it is best to use rewrite if you execute a task at a high frequency.QThread::run()way.

This is the article about the introduction to the use of QT thread QThread. For more related QT thread QThread content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!