I am using Qt5 where I am implementing a thread by passing the the QObject worker to a instance of QThread by moveToThread(). My implementation looks like this..
Worker.h
class worker : public QObject
{
Q_OBJECT
public:
explicit worker(QObject *parent = 0);
bool IsWorkRunning();
void MoveObjectToThread();
signal:
void SignalToObj_mainThreadGUI();
public slots:
void do_Work();
void StopWork();
void StartWork();
private:
void Sleep();
QThread *workerthread;
volatile bool running,stopped;
};
Worker.cpp
worker::worker(QObject *parent) :
QObject(parent),stopped(false),running(false)
{
}
void worker::do_Work()
{
running = true;
while(!stopped)
{
if(running)
{
emit SignalToObj_mainThreadGUI();
workerthread->msleep(20);
}
}
}
void worker::StopWork()
{
running = false;
}
void worker::StartWork()
{
running = true;
}
bool worker::IsWorkRunning()
{
return running;
}
void MoveObjectToThread()
{
workerthread = new QThread;
QObject::connect(workerthread,SIGNAL(started()),this,SLOT(do_Work()));
this->moveToThread(workerthread);
workerthread->start();
}
MainWindow.h
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void Startwork_mainwindow();
void Stopwork_mainwindow();
public slots:
private slots:
void on_pushButton_push_to_start_clicked();
void on_pushButton_push_to_stop_clicked();
private:
Ui::MainWindow *ui;
worker myWorker;
bool work_started;
};
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),work_started(false),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(this,SIGNAL(Startwork_mainwindow()),&myWorker,SLOT(StartWork()));
QObject::connect(this,SIGNAL(Stopwork_mainwindow()),&myWorker,SLOT(StopWork()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_push_to_start_clicked()
{
if(!work_started)
{
myWorker.MoveObjectToThread();
work_started = true;
}
if(!myWorker.IsWorkRunning())
emit this->Startwork_mainwindow();
}
void MainWindow::on_pushButton_push_to_stop_clicked()
{
if(myWorker.IsWorkRunning())
emit this->Stopwork_mainwindow();
}
Dont know why the following two signal/slot pair doesnt seem to work
QObject::connect(this,SIGNAL(Startwork_mainwindow()),&myWorker,SLOT(StartWork()));
QObject::connect(this,SIGNAL(Stopwork_mainwindow()),&myWorker,SLOT(StopWork()));
As a result i cant start or stop the thread once the do_Work()
slot is triggered by started()
signal of the QThread object. Just for reference this post of mine is a continuation of my previous post here described .Any insight will be helpful...thank you
moveToThread
, I would reimplementQThread
. It is easier to follow, and I think is less error prone. And when usingQObject::connect
from the main thread to another thread, don't connect to another thread usingAutoConnect
, useQueuedConnection
instead. – phyattQThread
. Look at this and the linked discussions for reasons why. stackoverflow.com/questions/4093159/… – g19fanatic