Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a simple Qt console application in C++?

Tags:

c++

console

qt

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.

like image 494
neuviemeporte Avatar asked Nov 14 '10 23:11

neuviemeporte


People also ask

Is Qt written in C?

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.

Is Qt only for C++?

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++.


1 Answers

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(); } 
like image 84
baysmith Avatar answered Oct 07 '22 20:10

baysmith