Signal/Slot doesn't work after moveToThread
-
I have implemented this approach to decouple the GUI from the Businesslayer:
main.c
@
#include "Core.h"int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
Core *core = new Core(&w);
w.show();return a.exec();
}
@IGui
@
class IGui
{
//--- slots
public:
virtual void onWorkFinished() = 0;//--- signals
signals:
void doWork();
};
@Core
@
#include "IGui.h"class Core : public QObject
{
Q_OBJECTpublic:
explicit Core(IGui *gui, QObject *parent = 0);signals:
void workFinished();private slots:
void onDoWork();private:
QThread m_workerThread;};
Core::Core(IGui *gui, QObject *parent) :
QObject(parent)
{
connect(dynamic_cast<QObject *>(gui), SIGNAL(doWork()),
this, SLOT(onDoWork()));
connect(this, SIGNAL(workFinished()),
dynamic_cast<QObject *>(gui), SLOT(onWorkFinished()));//this->moveToThread(&m_workerThread);
}void Core::onDoWork()
{
qDebug() << Q_FUNC_INFO;
QThread::msleep(1000);
emit workFinished();
}
@Dialog
@
#include "IGui.h"namespace Ui {
class Dialog;
}class Dialog : public QDialog, public IGui
{
Q_OBJECTpublic:
explicit Dialog(QWidget *parent = 0);
~Dialog();public slots:
void onWorkFinished();private slots:
void on_pushButton_clicked();private:
Ui::Dialog *ui;signals:
void doWork();
};Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}Dialog::~Dialog()
{
delete ui;
}void Dialog::onWorkFinished()
{
qDebug() << Q_FUNC_INFO;
}void Dialog::on_pushButton_clicked()
{
emit doWork();
}
@This works fine so far.
I want the onDoWork to be executed in a new thread so that the GUI is not blocked.
I thought I can do this by doing a moveToThread and then connect object.
But if I uncomment the moveToThread line the two signal/slot connections above doesn't work anymore.
So my first question is:
Why does they not work anymore?Second question is:
Is this the right way to achieve that the onDoWork runs in a new thread? -
I don't see you calling "start":http://qt-project.org/doc/qt-4.8/qthread.html#start on the m_workerThread object. So this would mean the thread is never started. So no running eventloop.
Another option to run the onDoWork() function in another thread would be to use "QtConcurrent":http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html .