I'm new to this but am wanting to write a Qt console app which uses Qt's features including signals and slots and therefore want an application event loop. Following this question How do I create a simple Qt console application in C++? I seem to be heading in the right direction but why does anything get executed after emitting finished in the following code:
// main.cpp
#include <QtCore>
#include <QDebug>
class Task : public QObject
{
Q_OBJECT
public:
Task(QObject *parent = 0) : QObject(parent) {}
public slots:
void run()
{
// Do processing here
qDebug() << "Hello World";
emit finished();
qDebug() << "I thought I'd finished!";
}
signals:
void finished();
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
Task *task = new Task(&a);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return a.exec();
}
Try to subclass the QCoreApplication and reimplement the quit() signal with inserting a debug print in.
You will see that the quit function is called immediately before your second print in the "run" slot, provided you are using DirectConnection
.
Also, worth nothing that quit() is slightly different to the GNU C exit() as per documentation:
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
This means quit() dos not mean that application quits right away without terminating gracefully in the middle of your method execution.