A good example for writing QThread with a GUI.
Here is another similar example:
QT5 TUTORIAL QTHREADS - GUI THREAD - 2020
Create a new class named MyThread, which inherits from QObject
This is what it looks like in the beginning in mythread.h
You can see that MyThread class, which inherits from QThread, is going to be added with some functions.
mythread.cpp
Once you key in the keyword “run”, a sequence of words automatically pops up. Press ENTER button
to add an override function easily.
Secondly, click right mouse button and a pop-up menu is shown. Choose “Refactor” and it will help you add its implenmentation of new function in mythread.cpp
Then add something in the run function.
And add a mechanics of stopping while-loop, like this
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread();
void run() override;
bool Stop = false;
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
MyThread::MyThread()
{
}
void MyThread::run()
{
for(int i=0; i<10000; i++)
{
if(this->Stop)
{
break;
}
qDebug() << QString::number(i);
this->msleep(10);
}
}
In case of dead-lock, a mutex lock and unlock should be added. So here it goes
void MyThread::run()
{
this->Stop = false;
for(int i=0; i<10000; i++)
{
QMutex mutex;
mutex.lock();
if(this->Stop)
{
break;
}
mutex.unlock();
qDebug() << QString::number(i);
this->msleep(10);
}
}
And now in order to display the number on the GUI instead of using qDebug. we are going to do two steps to complete it.
1. add a sender or say a signal named signalNumberChanged in mythread.h
2. add a receiver or say slot called slotNumberChanged in dialog.h.
mythread.h
mythread.cpp
dialog.h
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
th = new MyThread();
connect(th, SIGNAL(signalNumberChanged(int) ),
this, SLOT(slotNumberChanged(int)));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_start_clicked()
{
th->start();
}
void Dialog::on_pushButton_stop_clicked()
{
th->Stop =true;
}
void Dialog::slotNumberChanged(int counter)
{
//qDebug() << "slotNumberChanged:: " << QString::number(counter);
ui->label->setText(QString::number(counter));
}