The first Qt program in C++: qtHello

Dr. Nicola Mingotti
3 min readMay 19, 2022

We will write our first C++ program using the Qt libraries.

  • Why Qt ? In short [1] it has great documentation [2] it has been used to write great software [3] it is cross platform.
  • What the program does ? Being the first one it must print “hello world”, but we need to use the Qt library somehow. We don’t want to start with GUI stuff, we will start using very simple QDate objects. So, our program will just write the time in the local geographical location, then write also the Unix epoch in second and the current time in another city, say in Moscow.

First step, just a C++ program

  1. Make a directory to hold your project and go there
$> mkdir qtHello
$> cd qtHello

2. Write a very simple “qtHello.cpp” source file

#include<iostream>int main() { 
std::cout << "Hello World !\n";
std::cout.flush();
return 0;
}

3. Prepare a project file, a Makefile, compile and run the program

$> qmake -project 
# => a file "qtHello.pro" is created
$> qmake
# => a file "Makefile" is created
$> make
# => create the executable file "qtHello"
$> ./qtHello
Hello World !

4. Ok, up to now we didn’t use at all the power of Qt, but this was just to show that Qt is an extension to C++, you code in C++, Qt adds a lot of goodies to that.

Second step, let’s use a Qt class

5. So let’s try to use the QDate class to get the current date and time. You are invited to follow this link and read the GREAT documentation. Change the qtHello.cpp as follow

#include<iostream>
#include<QDate>
int main() {
std::cout << "Hello World";
QDateTime d;
d = QDateTime::currentDateTime();
QString qs;
qs = d.toString("', at: 'HH:MM - ddd dd MMM yyyy");
std::cout << qs.toStdString() << "\n";
std::cout.flush();
return 0;
}

Then compile and run to get

$> make 
$> ./qtHello
# => Hello World, at: 12:05 - Thu 19 May 2022

That’s it, we made and used the first Qt program.

Third step, let’s get more sophisticated

Ok, we are using a professional toolkit, we want something more that a simple date. We want a localized date and the UTC date. So, let’s say, I want the current date time in Moscow time, Rome and UTC.

Compile and run it, many time may be, to get what you want with

$> make && echo " ================== " && ./qtHello

The output you see will be something like

Final thoughts

FT1. If you look into the top part of the page in QDate or QTimeZone or QString you will see all of them start with something like this:

These classes are in the “package” called “core” which is by default included in a Qt project. We will see in next examples this is not the case in general.

FT2. The namespace std is loaded by #include<iostream>. I prefer not to include all the names there, which can be accomplished with using namespace std; before the main function.

--

--