qt c++ thread example

To create a simple multi-threaded application using Qt and C++, follow these steps:

  1. Create a new Qt Console Application project in Qt Creator.
  2. In the main.cpp file, include the necessary headers:
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
  1. Define a new class that inherits from QThread. Override the run() method to specify the code that will run in the new thread:
class MyThread : public QThread {
public:
    void run() override {
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Hello from thread" << QThread::currentThread();
            QThread::sleep(1);
        }
    }
};
  1. In the main function, create an instance of the custom thread class and start the thread:
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    MyThread thread;
    thread.start();

    for (int i = 0; i < 5; ++i) {
        qDebug() << "Hello from main" << QThread::currentThread();
        QThread::sleep(1);
    }

    return a.exec();
}
  1. Build and run the project. You should see output from both the main thread and the custom thread, demonstrating that they are running concurrently.