This time we are going to create a new Object intead of using subclass of QThread,
and all its job is transfer to a QThread instance by calling moveToThread method.
You can find out details on youtube.
Let’s create a new project of window application and add new class, in which it accumaltes from 1 to 999.
This is what it looks like after setting up previous settings.
1. Two heards <QThread> and <QDebug> are added
2. A slot named “DoJob” takes responsibility of doing something.
3. A public method “DoSetup” is passing a reference to this thread that it will asign current job to be run in the thread.
4.NumberChanged is used to notify the GUI for displaying the current number
myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QMutex>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = nullptr);
void DoSetup(QThread &thread);
bool Stop;
signals:
void NumberChanged(int number);
public slots:
void DoJob();
};
#endif // MYOBJECT_H
myobject.cpp
#include "myobject.h"
MyObject::MyObject(QObject *parent) : QObject(parent)
{
}
void MyObject::DoSetup(QThread &thread)
{
// connect the slot named DoJob to a signal, which is emitted by another thread
connect(&thread, SIGNAL(started()), this, SLOT(DoJob()));
this->Stop = false;
}
void MyObject::DoJob()
{
for(int i=0; i<1000; i++)
{
// if ( QThread::currentThread()->isInterruptionRequested() )
// break;
QMutex mutex;
mutex.lock();
if(Stop)
{
break;
}
mutex.unlock();
emit NumberChanged(i);
this->thread()->msleep(10);
}
}
//myThread.quit();
dialog.cpp
When start button clicks, myObject put itself into anther thread by a method called moveToThread.
The job of myObject is going to run as soon as the thread get started.
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
// myobject informs the GUI that the number has changed
connect(&myObject, SIGNAL(NumberChanged(int)), this, SLOT(on_NumberChanged(int)));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_Start_clicked()
{
// This time we create a new Object intead of using subclass of QThread,
// and all its job is transfer to a QThread instance by calling moveToThread method
myObject.DoSetup(myThread);
myObject.moveToThread(&myThread);
myThread.start();
}
void Dialog::on_pushButton_Stop_clicked()
{
myObject.Stop = true;
int retCode = 0;
myThread.exit(retCode);
//qDebug() << QString::number(retCode);
}
void Dialog::on_NumberChanged(int number)
{
ui->label_number->setText(QString::number(number));
}
Reference:
1. C++ Qt 35 - QThread part 6 - Threading done correctly in Qt