The Simple Use of QT hread

Keywords: Qt

Description of the use of QThread: The thread class of QThread is already encapsulated. If you want to use threads, you can derive subclasses and implement the thread interface function run (run is the thread task function).

Next, we use the QThread to achieve the acquisition of the current system time and display it on the main interface (UI thread). The implementation method is to collect the system time in the sub-thread, send the signal to the UI thread, and display it on the UI thread.

1. In the QT project, create a new class and inherit the QThread

2. Time of acquisition system realized by sub-thread class

Header file (timethread.h) code

1. In order to make our subclasses very similar to the existing QThread classes of the QT, we changed the constructor of our derived classes to the same constructor as that of the parent class.

2. The sending time is sent to UI threads through signals, and Q_OBJECT is needed to use the signal and slot functions.

Specific code

#ifndef TIMETHREAD_H
#define TIMETHREAD_H

#include <QObject>
#include <QThread>

class TimeThread : public QThread
{
    Q_OBJECT //Using Signal and Slot Functions
public:
    explicit TimeThread(QObject *parent = nullptr);
    //Implementing run Interface
    void run();
//Declaration signal
signals:
    void sendTime(QString );
};

#endif // TIMETHREAD_H

Cpp file (timethread.cpp) code

Through the interface function run, the current system time is acquired every 1 second, and the signal is sent out by emit.

#include "timethread.h"
#include <QTime>
#include <QDebug>
TimeThread::TimeThread(QObject *parent):QThread(parent)
{

}
void TimeThread::run()
{
    //Thread task
    while(1)
    {
        qDebug()<<currentThreadId();
        QString t = QTime::currentTime().toString("hh:mm:ss");
        //delayed
        sleep(1);
        //Send time by signal
        emit sendTime(t);
    }
}

III. UI Interface Design

IV. Specific Implementation of UI Threads

1. SendTime sent by associative word threads

2. Start and stop threads by two buttons

3. Display the received time on the LCD screen

Specific code

#include "threadshowtime.h"
#include "ui_threadshowtime.h"

ThreadShowTime::ThreadShowTime(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ThreadShowTime)
{
    ui->setupUi(this);
    //sendTime signal for associated threads
    connect(&th, &TimeThread::sendTime, this, &ThreadShowTime::show_time);
}

ThreadShowTime::~ThreadShowTime()
{
    delete ui;
}

void ThreadShowTime::on_startBt_clicked()
{
    //Startup thread
    th.start();
}

void ThreadShowTime::on_stopBt_clicked()
{
    //Thread stop
    th.terminate();
}

void ThreadShowTime::show_time(QString t)
{
    ui->lcdNumber->display(t);
}

V. Effect demonstration

 

Posted by SyndicatE on Mon, 30 Sep 2019 09:54:21 -0700