I was trying to create a simple console application to try out Qt's XML parser. I started a project in VS2008 and got this template:
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); return a.exec(); }
Since I don't need event processing, I was wondering whether I may get into trouble if I neglect to create a QCoreApplication and running the event loop. The docs state that it's recommended in most cases.
For the sake of curiosity however, I am wondering how could I make some generic task execute on the event loop and then terminate the application. I was unable to google a relevant example.
Qt is not a programming language on its own. It is a framework written in C++. A preprocessor, the MOC (Meta-Object Compiler), is used to extend the C++ language with features like signals and slots.
While the Qt framework is C++ based, you can also code with QML and JavaScript. In fact, you can create full apps without even touching C++.
Here is one simple way you could structure an application if you want an event loop running.
// main.cpp #include <QtCore> class Task : public QObject { Q_OBJECT public: Task(QObject *parent = 0) : QObject(parent) {} public slots: void run() { // Do processing here emit 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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With