Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

Qt/C++ - Lesson 047. QThread – How to make threads in Qt

Qt, QThread, потоки

One of the most common ways to create a separate parallel threads in an application to Qt , and perform useful tasks in them is the inheritance of QThread class and override the method run() , which will be carried out and useful application code. When meeting with threads have read different opinions on this subject, and in this lesson will get acquainted with one of the possible ways to work with streams, but which are not considered to be the best option.

In general, if we make the class inherit from the QThread , it is logical to assume that this is done with the intention that it is not sufficient functionality of the class. But when this is done only with the aim to bring in, which must be performed in a separate thread run() method a useful code, then there is clearly something wrong. In addition, de might be a problem with scaling applications and reuse code, particularly hard this can be shown in the case where such inherited class becomes quite a lot.

This method is the low level, and is used primarily for customization native streams. What is somewhat contrary to the usual need to complete a task in a separate thread. That is, as mentioned above, such an approach is primarily needed to extend the functionality class. Nevertheless, this method is necessary to consider what and proceed.


This example is very small, so we will not go into the details of the project structure. Note that there will be created a console application in the file main.cpp which will create three streams with different names. A stream classes will be inherited from QThread .

#include <QCoreApplication>
#include "examplethreads.h"

int main(int argc, char *argv[])
    QCoreApplication a(argc, argv);

    ExampleThreads threadA("thread A"); 
    ExampleThreads threadB("thread B"); 
    ExampleThreads threadC("thread C");

    threadA.start();    // Run threads
    threadB.start();    // and seeing their parallel operation
    threadC.start();    // in the output qDebug

    return a.exec();



#include <QThread>

class ExampleThreads : public QThread
    explicit ExampleThreads(QString threadName);

    // Override run () method, which will be located 
    // executable code
    void run();
    QString name;   // thread name



#include "examplethreads.h"
#include <QDebug>

ExampleThreads::ExampleThreads(QString threadName) :


void ExampleThreads::run()
    for (int i = 0; i <= 100; i++ ) {
        qDebug() << name << " " << i;

Output threads



Only authorized users can post comments.
Please, Log in or Sign up
Feb. 18, 2019, 3:39 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Feb. 15, 2019, 1:03 p.m.
Николай Булахтин

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
Feb. 14, 2019, 6:41 p.m.

Спасибо огромное! Заработало!
Feb. 12, 2019, 9:26 a.m.

Сам разборался, спасибо.
Feb. 12, 2019, 8:19 a.m.

День добрый! Можешь выложить форму mainwindow.ui от урока? Заранее спасибо
Feb. 11, 2019, 10:51 a.m.
Евгений Легоцкой

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.
Now discuss on the forum
Feb. 17, 2019, 5:28 p.m.
Евгений Легоцкой

Добрый день. Очень извиняюсь за долгий ответ Первое, что нашёл, так это необходимость перерисовать чекбокс. void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem ...
Feb. 15, 2019, 3:36 p.m.
Евгений Легоцкой

Ну я тут нашёл одно решение, но сам его не проверял. Вам нужно помещать фамилии скорее всего в ячейки заголовка, и потом просто перерисовывать их QHeaderView * header = m_ui->tableWidget...
Feb. 15, 2019, 7:53 a.m.
Евгений Легоцкой

Добрый день! Не работал с remoteobjects, поэтому глянул документацию, чтобы рассмотреть, что это за зверь. После просмотра документации сложилось стойкой впечатление, что это вполне возм...
Feb. 14, 2019, 6:28 p.m.

Нашел решение на Java. Удалось интегрировать в проект сервиса на Qt, теперь из Qt запускаю Java-код акселерометра.
Join us in social networks

For registered users on the site there is a minimum amount of advertising