So new to Qt. Read the wiki and C++ Gui programming book and they say subclass QThread. Found that this is not the recommended way now.
So I have some practice code here and I have some questions about if this is correct. So I would really appreciate someone having a look please.
So I created a class with the QThread as a private member to use for the movetothread. When creating it, I made sure not to specify a parent. Therefore my first question is, is this ok to do?
Second question comes from the m_thread->quit(); I found that my connect to finished wasn't being emitted until I did this. So is this the correct way? I read http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ and saw that the connect between finished and deleteLater in the same thread but not 100% sure if this should be used with quit.
Finally, with the talk of deleteLater, does this mean I dont need delete m_thread
Thanks for anyones time.
Code here. Simple QDialog with a pushbutton. worker.cpp
#include "worker.h"
worker::worker(QObject *parent) :
QObject(parent)
{
stopped = false;
}
void worker::setupAndRun()
{
m_thread = new QThread();
connect(m_thread,SIGNAL(started()),this,SLOT(doWork()));
connect(m_thread,SIGNAL(finished()),this,SLOT(onComplete()));
connect(m_thread,SIGNAL(finished()),m_thread,SLOT(deleteLater()));
this->moveToThread(m_thread);
m_thread->start();
}
void worker::doWork()
{
for(int i = 0; i < 20000; i++)
{
if (this->stopped)
break;
qDebug() << i << " : " << Q_FUNC_INFO << m_thread->currentThreadId();
}
// --- I think the quit calls the finished signal?
m_thread->quit();
}
void worker::onComplete()
{
qDebug() << Q_FUNC_INFO << "Called " << m_thread->currentThreadId();
}
worker.h
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QDebug>
#include <QThread>
class worker : public QObject
{
Q_OBJECT
public:
explicit worker(QObject *parent = 0);
void setupAndRun();
signals:
public slots:
void doWork();
void onComplete();
private:
// --- The thread that I use to movetothread with.
// Is this ok?
QThread *m_thread;
bool stopped;
};
#endif // WORKER_H
Dialog push button
void Dialog::on_pushButton_clicked()
{
m_worker = new worker();
m_worker->setupAndRun();
}