#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QDebug>
#include <QThread>
class Worker : public QObject
{
Q_OBJECT
public:
Worker()
{
qDebug() << "ctor Worker";
}
~Worker()
{
qDebug() << "dtor Worker";
}
void doWork()
{
qDebug() << "working";
}
signals:
void resultReady();
};
class Controller : public QObject
{
Q_OBJECT
QThread thread;
public:
Controller()
{
Worker* worker = new Worker;
worker->moveToThread(&thread);
connect(this, &Controller::start, worker, &Worker::doWork);
connect(worker, &Worker::resultReady, this, &Controller::handleResults);
thread.start();
}
~Controller()
{
thread.quit();
thread.wait();
}
public slots:
void handleResults()
{
qDebug() << "results done.";
}
signals:
void start();
};
class Widget : public QWidget
{
Q_OBJECT
QHBoxLayout hLayout;
QPushButton bt;
Controller& core;
public:
Widget(Controller& c)
: QWidget(), core(c)
{
setLayout(&hLayout);
hLayout.addWidget(&bt);
bt.setText("ok");
connect(&bt, &QPushButton::clicked, &core, &Controller::start);
}
};
#include "main.moc"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Controller core;
Widget w{core};
w.resize(400, 300);
w.show();
return app.exec();
}
In the above I think we are missing
delete worker
Anyway the program terminates with code 0.
The Worker destructor isn't called, right? Still program terminates with code 0. Is everything fine?
Is there any technique I can use while coding in order to prevent program to return 0 when there is a leak? I guess the answer is smart pointers but Qt connect requires raw pointer?