Qt for command-line use

Even though the graphical user interface is a big selling point of the Qt framework, it is also possible to use it to develop command-line-only applications. For this, we just use the QCoreApplication class to create an input and an event loop handler, as in this example:

#include <QCoreApplication> 
#include <core.h> 
 
int main(int argc, char *argv[]) { 
   QCoreApplication app(argc, argv); 
   Core core; 
 
   connect(&core, &Core::done, &app, &app::quit, Qt::QueuedConnection); 
   core.start(); 
 
   return app.exec(); 
} 

Here, our code is implemented in a class called Core. In the main function, we create a QCoreApplication instance, which receives the command-line parameters. We then instantiate an instance of our class.

We connect a signal from our class to the QCoreApplication instance, so that if we signal that we have finished, it will trigger a slot on the latter to clean up and terminate the application.

After this, we call the method on our class to start its functionality and finally start the event loop by calling exec() on the QCoreApplication instance. At this point, we can use signals.

Note here that it is also possible to use Qt4-style connection syntax, instead of the earlier Qt5-style:

connect(core, SIGNAL(done()), &app, SLOT(quit()), Qt::QueuedConnection); 

Functionally, this makes no difference, and using either is fine for most situations.

Our class appears as follows:

#include <QObject> 
 
class Core : public QObject { 
   Q_OBJECT 
public: 
   explicit Core(QObject *parent = 0); 
 
signals: 
   void done(); 
public slots: 
   void start(); 
}; 

Every class in a Qt-based application that wants to make use of the signal-slot architecture of Qt is required to derive from the QObject class, and to include the Q_OBJECT macro within the class declaration. This is needed for Qt's qmake preprocessor tool to know which classes to process before the application code is compiled by the toolchain.

Here is the implementation:

#include "core.h" 
#include <iostream> 
 
Core::Core(QObject *parent) : QObject(parent) { 
   // 
} 
 
void hang::start() { 
   std::cout << "Start emitting done()" << std::endl; 
   emit done(); 
} 

Of note is the fact that we can let the constructor of any QObject-derived class know what the encapsulating parent class is, allowing said parent to own these child classes and invoke their destructor when it itself is destroyed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.87.156