QCoreApplication says hello

Usually we use Qt to develop a GUI application, but that is not mandatory. We could be interested in developing an application using a feature made available by Qt, like the network or XML support, without any explicit need for a graphical interface.

In this case we can develop a console application, that rely on QCoreApplication, instead of the usual QApplication, to provide an even loop for the application.

As an example, here is a trivial application, that says hello and then terminates. To make the code slightly more interesting, I create a class, Greeter, that provides a slot, sayHello(), to be called to greet the user:
#ifndef GREETER_H
#define GREETER_H

#include <QObject>
#include <iostream>

class Greeter : public QObject
explicit Greeter(QObject *parent = 0) : QObject(parent) {}


public slots:
void sayHello() { std::cout << "Hello" << std::endl; }
#endif // GREETER_H

And here is the main:
#include <QtCore/QCoreApplication>
#include <QTimer>
#include "greeter.h"

int main(int argc, char *argv[])
QCoreApplication a(argc, argv);

Greeter g;
QTimer::singleShot(2000, &g, SLOT(sayHello())); // 1.
QTimer::singleShot(5000, &a, SLOT(quit())); // 2.

g.sayHello(); // 3.
return a.exec(); // 4.

1. We use QTimer to do a delayed call (by 2 secs) to g.sayHello().
2. After 5 secs we'll call the quit() method for our QCoreApplication object, that will have the effect of terminating the call to exec().
3. We call immediately g.sayHello().
4. The Qt application enters the main event loop - that will be interrupted by the delayed call to quit().

No comments:

Post a Comment