Saturday, April 27, 2013

First programs in Qt4

In this part of the Qt4 C++ programming tutorial, we will create our first programs.
We will display an application icon, a tooltip and various mouse cursors. We will center a window on the screen and introduce the signal & slot mechanism.

Simple example

We start with a very simple example.
#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;

    window.resize(250, 150);
    window.setWindowTitle("Simple example");
    window.show();

    return app.exec();
}
We will show a basic window on the screen.
#include <QApplication>
#include <QWidget>
We include necessary header files.
QApplication app(argc, argv);
This is the application object. Each application programmed in Qt4 must have this object. Except for console applications.
QWidget window;
This is our main widget.
 window.resize(250, 150);
 window.setWindowTitle("Simple example");
 window.show();
Here we resize the widget. Set a title for our main window. In this case, the QWidget is our main window. And finally show the widget on the screen.
 return app.exec();
We start the main loop of the application.
Simple example
Figure: Simple example

Centering the window

If we do not position the window ourselves, the window manager will position it for us. In the next example, we will center the window.
#include <QApplication>
#include <QDesktopWidget>
#include <QWidget>

int main(int argc, char *argv[])
{

  int WIDTH = 250;
  int HEIGHT = 150;

  int screenWidth;
  int screenHeight;

  int x, y;

  QApplication app(argc, argv);

  QWidget window;

  QDesktopWidget *desktop = QApplication::desktop();

  screenWidth = desktop->width();
  screenHeight = desktop->height(); 

  x = (screenWidth - WIDTH) / 2;
  y = (screenHeight - HEIGHT) / 2;

  window.resize(WIDTH, HEIGHT);
  window.move( x, y );
  window.setWindowTitle("Center");
  window.show();

  return app.exec();
}
There are plenty of monitor sizes and resolution types. In order to center a window, we must determine the desktop width and height. For this, we use the QDesktopWidget class.
QDesktopWidget *desktop = QApplication::desktop();

screenWidth = desktop->width();
screenHeight = desktop->height(); 
Here we determine the screen width and height.
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
Here we compute the upper left point of our centered window.
window.resize(WIDTH, HEIGHT);
window.move( x, y );
We resize the widget and move it to the computed position. Note, that we must first resize the widget. We move it afterwards.

A tooltip

A tooltip is a specific hint about a tool in an application. The following example will demonstrate, how we can create a tooltip in Qt4 programming library.
#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);  

  QWidget window;

  window.resize(250, 150);
  window.move(300, 300);
  window.setWindowTitle("ToolTip");
  window.setToolTip("QWidget");
  window.show();

  return app.exec();
}
Creating a tooltip is easy. All we do is call the setToolTip() method.
window.setWindowTitle("ToolTip");
We set a tooltip for the QWidget widget.
A tooltip
Figure: A tooltip

The application icon

In the next example, we show the application icon. Most window managers display the icon in the left corner of the titlebar and also on the taskbar.
#include <QApplication>
#include <QWidget>
#include <QIcon>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);  
    
  QWidget window;

  window.resize(250, 150);
  window.move(300, 300);
  window.setWindowTitle("icon");
  window.setWindowIcon(QIcon("web.png"));
  window.show();

  return app.exec();
}
An icon is shown in the upper left corner of the window.
window.setWindowIcon(QIcon("web.png"));
To display an icon, we use the setWindowIcon() method and a QIcon class. The icon is a small PNG file located in the current working directory.
Icon
Figure: Icon

Cursors

A cursor is a small icon that indicates the position of the mouse pointer. In the next example will show various cursors that we can use in our programs.
#include <QApplication>
#include <QWidget>
#include <QFrame>
#include <QGridLayout>


class Cursors : public QWidget
{
 public:
     Cursors(QWidget *parent = 0);
};


Cursors::Cursors(QWidget *parent)
    : QWidget(parent)
{  
  QFrame *frame1 = new QFrame(this);
  frame1->setFrameStyle(QFrame::Box);
  frame1->setCursor(Qt::SizeAllCursor);

  QFrame *frame2 = new QFrame(this);
  frame2->setFrameStyle(QFrame::Box);
  frame2->setCursor(Qt::WaitCursor);

  QFrame *frame3 = new QFrame(this);
  frame3->setFrameStyle(QFrame::Box);
  frame3->setCursor(Qt::PointingHandCursor);

  QGridLayout *grid = new QGridLayout(this);
  grid->addWidget(frame1, 0, 0);
  grid->addWidget(frame2, 0, 1);
  grid->addWidget(frame3, 0, 2);

  setLayout(grid);
}


int main(int argc, char *argv[])
{
  QApplication app(argc, argv);  
    
  Cursors window;

  window.resize(350, 150);
  window.move(300, 300);  
  window.setWindowTitle("cursors");
  window.show();

  return app.exec();
}
In this example, we will use three QFrames. Each of the frames will have a different cursor defined.
QFrame *frame1 = new QFrame(this);
frame1->setFrameStyle(QFrame::Box);
frame1->setCursor(Qt::SizeAllCursor);
This will create a frame widget. We set a specific frame style and a cursor type.
QGridLayout *grid = new QGridLayout(this);
grid->addWidget(frame1, 0, 0);
grid->addWidget(frame2, 0, 1);
grid->addWidget(frame3, 0, 2);
setLayout(grid);
This will group all the frames. We will talk more about this in the layout management section.

A button

In the next code example, we display a push button on the window. By clicking on the button we close the application.
#include <QApplication>
#include <QWidget>
#include <QPushButton>

class MyButton : public QWidget
{
 public:
     MyButton(QWidget *parent = 0);
};

MyButton::MyButton(QWidget *parent)
    : QWidget(parent)
{   
  QPushButton *quit = new QPushButton("Quit", this);
  quit->setGeometry(50, 40, 75, 30);

  connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
}


int main(int argc, char *argv[])
{
  QApplication app(argc, argv);  
    
  MyButton window;

  window.resize(250, 150);
  window.move(300, 300);
  window.setWindowTitle("button");
  window.show();

  return app.exec();
}
In this code example, we use the concept of the signals & slots for the first time.
QPushButton *quit = new QPushButton("Quit", this);
quit->setGeometry(50, 40, 75, 30);
We create a new QPushButton. We manually place it to the x:50px, y:40px position and resize it to width:75px, height:30px.
connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
When we click on the button, a clicked() signal is generated. The slot is the method, which will react to the signal. In our case it is the quit() slot of the main application object. The qApp is a global pointer to the application object. It is defined in the QApplication header file.
A button
Figure: A button

Communicate

We will finish this section showing, how widgets can communicate together. We will split the code into three files. So far we have used only one file. This is possible only in small examples. Now we will have three source files.
communicate.h
#ifndef COMMUNICATE_H
#define COMMUNICATE_H

#include <QWidget>
#include <QApplication>
#include <QPushButton>
#include <QLabel>

class Communicate : public QWidget
{
  Q_OBJECT

  public:
    Communicate(QWidget *parent = 0);


  private slots:
    void OnPlus();
    void OnMinus();

  private:
    QLabel *label;

};

#endif
This is the header file of the example. In this file, we define two slots and a label widget.
communicate.cpp
#include "communicate.h"

Communicate::Communicate(QWidget *parent)
    : QWidget(parent)
{
  QPushButton *plus = new QPushButton("+", this);
  plus->setGeometry(50, 40, 75, 30);

  QPushButton *minus = new QPushButton("-", this);
  minus->setGeometry(50, 100, 75, 30);

  label = new QLabel("0", this);
  label->setGeometry(190, 80, 20, 30);

  connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
  connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));
}

void Communicate::OnPlus()
{
  int val = label->text().toInt();
  val++;
  label->setText(QString::number(val));
}

void Communicate::OnMinus()
{
  int val = label->text().toInt();
  val--;
  label->setText(QString::number(val));
}
We have two push buttons and a label widget. We increase/decrease the number displayed by the label with the buttons.
connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));
Here we connect the clicked() signals to the slots.
void Communicate::OnPlus()
{
  int val = label->text().toInt();
  val++;
  label->setText(QString::number(val));
}
In the OnPlus() method, we determine the current value of the label. The label widget displays a string value, so we must convert it to the integer. We increase the number and set a new text for the label. We convert a number to the string value.
main.cpp
#include "communicate.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  Communicate window;

  window.setWindowTitle("Communicate");
  window.show();

  return app.exec();
}
This is the main file of the code example.
Communicate
Figure: Communicate
In this chapter, we created our first programs in Qt4.

Date and time in Qt4

In this part of the Qt4 C++ programming tutorial, we will talk about time and date.
Qt4 has QDate, QTime and QDateTime classes to work with date and time. The QDate is a class for working with a calendar date in the Gregorian calendar. It has methods for determining the date, comparing or manipulating dates. The QTime class works with a clock time. It provides methods for comparing time, determining the time and various other time manipulating methods. The QDateTime is a class that combines both QDate and QTime objects into one object.

Initializing date & time objects

Date and time objects can be initialized in two basic ways. We initialize them in the object constructor or we can create empty objects and fill them with data later.
init.cpp
#include <QTextStream>
#include <QDate>
#include <QTime>

int main(void)
{
   QTextStream out(stdout);

   QDate dt1(2011, 4, 12);
   out << "The date is " << dt1.toString() << endl;
   
   QDate dt2;
   dt2.setDate(2011, 3, 3);
   out << "The date is " << dt2.toString() << endl;

   QTime tm1(17, 30, 12, 55);
   out << "The time is " << tm1.toString("hh:mm:ss.zzz") << endl;
   
   QTime tm2;
   tm2.setHMS(13, 52, 45, 155);
   out << "The time is " << tm2.toString("hh:mm:ss.zzz") << endl;     
}
We initialize date and time object in both ways.
QDate dt1(2011, 4, 12);
The QDate object constructor takes three parameters. The year, the month and the day.
out << "The date is " << dt1.toString() << endl;
The date is printed to the console. We use the toString() method to convert the date object into string.
QTime tm2;
tm2.setHMS(13, 52, 45, 155);
An empty QTime object is created. We fill the object with data using the setHMS() method. The parameters are the hours, minutes, seconds and the miliseconds.
out << "The time is " << tm2.toString("hh:mm:ss.zzz") << endl;   
We print the QTime object to the console. We use a specific format that includes also the miliseconds, which are omitted by default.
Output
$ ./simple 
The date is Tue Apr 12 2011
The date is Thu Mar 3 2011
The time is 17:30:12.055
The time is 13:52:45.155

Current date & time

In the following example, we print the current local time and date to the console.
curdatetime.cpp
#include <QTextStream>
#include <QTime>
#include <QDate>

int main()
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   QTime ct = QTime::currentTime();
   
   out << "Current date is " << cd.toString() << endl;
   out << "Current time is " << ct.toString() << endl;      
}
Watch out that the file must not be called time.cpp.
QDate cd = QDate::currentDate();
The QDate::currentDate() static function returns the current date.
QTime ct = QTime::currentTime();
The QTime::currentTime() static function returns the current time.
out << "Current date is " << cd.toString() << endl;
out << "Current time is " << ct.toString() << endl; 
We use the toString() method to convert the date and time objects to strings.
Output
$ ./curdatetime 
Current date is Tue Sep 18 2012
Current time is 19:43:37

Comparing dates

Relational operators can be used to compare dates. We can compare their position in the calendar.
comparedates.cpp
#include <QTextStream>
#include <QDate>

int main()
{
   QTextStream out(stdout);

   QDate dt1(2012, 4, 5);
   QDate dt2(2011, 4, 5);
   
   if (dt1 < dt2) {
       out << dt1.toString() << " comes before "
       << dt2.toString() << endl;
   } else {
       out << dt1.toString() << " comes after "
       << dt2.toString() << endl;
   }   
}
The example compares two dates.
QDate dt1(2012, 4, 5);
QDate dt2(2011, 4, 5);
We have two different dates.
if (dt1 < dt2) {
    out << dt1.toString() << " comes before "
    << dt2.toString() << endl;
} else {
    out << dt1.toString() << " comes after "
    << dt2.toString() << endl;
}   
We compare the dates with a lower than (<) comparison operator and determine which of them is located earlier in the calendar.
Output
$ ./comparedates 
Thu Apr 5 2012 comes after Tue Apr 5 2011
Comparison operators can be easily used for QTime and QDateTime objects too.

Determining a leap year

A leap year is a year containing an additional day. The reason for an extra day in the calendar is the difference between the astronomical and the calendar year. The calendar year has exactly 365 days, while the astronomical year, the time for the earth to make one revolution around the Sun, is 365.25 days. The difference is 6 hours which means that in four years time we are missing one day. Because we want to have our calendar synchronized with the seasons, we add one day to February each four years. (There are exceptions.) In the Gregorian calendar, February in a leap year has 29 days instead of the usual 28. And the year lasts 366 days instead of the usual 365.
The QDate::isLeapYear() static method determines, whether a year is a leap year or not.
leapyear.cpp
#include <QTextStream>
#include <QDate>

int main()
{
   QTextStream out(stdout);

   
   if (QDate::isLeapYear(2010)) {
       out << "2010 is a leap year" << endl;
   } else {
       out << "2010 is not a leap year" << endl; 
   }
   
   if (QDate::isLeapYear(2011)) {
       out << "2011 is a leap year" << endl;
   } else {
       out << "2011 is not a leap year" << endl;
   }
   
   if (QDate::isLeapYear(2012)) {
       out << "2012 is a leap year" << endl;
   } else {
       out << "2012 is not a leap year" << endl;
   }         
}
We check three years and print if they are leap years or not leap years.
if (QDate::isLeapYear(2010)) {
    out << "2010 is a leap year" << endl;
} else {
    out << "2010 is not a leap year" << endl; 
}
Here we check if the year 2010 is a leap year. We print a message accordingly to the terminal. The QDate::isLeapYear() returns a boolean true or false.
Output
$ ./leapyear 
2010 is not a leap year
2011 is not a leap year
2012 is a leap year

Predefined date formats

Qt4 has some built-in date formats. The toString() method of a QDate object takes a date format as a parameter. The default date format used by Qt4 is Qt::TextDate.
dateformats.cpp
#include <QTextStream>
#include <QDate>

int main(void)
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   
   out << "Today is " << cd.toString(Qt::TextDate) << endl;
   out << "Today is " << cd.toString(Qt::ISODate) << endl;
   out << "Today is " << cd.toString(Qt::SystemLocaleShortDate) << endl;
   out << "Today is " << cd.toString(Qt::SystemLocaleLongDate) << endl;
   out << "Today is " << cd.toString(Qt::DefaultLocaleShortDate) << endl;
   out << "Today is " << cd.toString(Qt::DefaultLocaleLongDate) << endl;
   out << "Today is " << cd.toString(Qt::SystemLocaleDate) << endl;
   out << "Today is " << cd.toString(Qt::LocaleDate) << endl;   
}
In the example, we show 8 different date formats for the current date.
out << "Today is " << cd.toString(Qt::ISODate) << endl;
Here we print the current date in the Qt::ISODate format, which is an international standard for displaying dates.
Output
$ ./dateformats 
Today is Wed Sep 19 2012
Today is 2012-09-19
Today is 9/19/12
Today is Wednesday, September 19, 2012
Today is 9/19/12
Today is Wednesday, September 19, 2012
Today is 9/19/12
Today is 9/19/12

Custom date formats

A date can be represented in a variety of other formats. In Qt4 we can create our custom date formats. Another version of the toString() method takes a format string where we can use various format specifiers. For example the d specifier stands for a day as a number without a leading zero. The dd specifier stands for a day as a number with a leading zero. The following table lists available date format expressions.
ExpressionOutput
dThe day as a number without a leading zero (1 to 31)
ddThe day as a number with a leading zero (01 to 31)
dddThe abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName().
ddddThe long localized day name (e.g. 'Monday' to 'Sunday'). Uses QDate::longDayName().
MThe month as a number without a leading zero (1 to 12)
MMThe month as a number with a leading zero (01 to 12)
MMMThe abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName().
MMMMThe long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName().
yyThe year as two digit number (00 to 99)
yyyyThe year as four digit number. If the year is negative, a minus sign is prepended in addition.
Table: Date format specifiers
customdateformats.cpp
#include <QTextStream>
#include <QDate>

int main(void)
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   
   out << "Today is " << cd.toString("yyyy-MM-dd") << endl;
   out << "Today is " << cd.toString("yy/M/dd") << endl;
   out << "Today is " << cd.toString("d.M.yyyy") << endl;
   out << "Today is " << cd.toString("d-MMMM-yyyy") << endl; 
}
We have four custom date formats.
out << "Today is " << cd.toString("yyyy-MM-dd") << endl;
This is the international date format. The parts of the date are separated by a dash character. The yyyy is a year having four digits. The MM is the the month as number with a leading zero. (01 to 12) And the dd is the day as number with a leading zero (01 to 31).
out << "Today is " << cd.toString("yy/M/dd") << endl;
This is another common date format. The parts are separated by a slash (/) character. The M specifier stands for a month as number without a leading zero (1 to 12).
out << "Today is " << cd.toString("d.M.yyyy") << endl;
This date format is used in Slovakia. The parts are separated by a dot character. The day and month are without leading zeros. First is the day, then comes the month and the last is the year.
Output
$ ./customdateformats 
Today is 2012-09-19
Today is 12/9/19
Today is 19.9.2012
Today is 19-September-2012

Predefined time formats

Time has some predefined formats. The standard format specifiers are identical to those used in the date formats. The default time format used by Qt4 is Qt::TextDate.
timeformats.cpp
#include <QTextStream>
#include <QTime>

int main(void)
{
   QTextStream out(stdout);

   QTime ct = QTime::currentTime();
   
   out << "The time is " << ct.toString(Qt::TextDate) << endl;
   out << "The time is " << ct.toString(Qt::ISODate) << endl;
   out << "The time is " << ct.toString(Qt::SystemLocaleShortDate) << endl;
   out << "The time is " << ct.toString(Qt::SystemLocaleLongDate) << endl;
   out << "The time is " << ct.toString(Qt::DefaultLocaleShortDate) << endl;
   out << "The time is " << ct.toString(Qt::DefaultLocaleLongDate) << endl;
   out << "The time is " << ct.toString(Qt::SystemLocaleDate) << endl;
   out << "The time is " << ct.toString(Qt::LocaleDate) << endl;   
}
In the example, we show 8 different time formats for the current time.
out << "The time is " << ct.toString(Qt::ISODate) << endl;
Here we print the current time in the Qt::ISODate format, which is an international standard for displaying times.
Output
$ ./timeformats 
The time is 08:12:52
The time is 08:12:52
The time is 8:12 AM
The time is 8:12:52 AM CEST
The time is 8:12 AM
The time is 8:12:52 AM CEST
The time is 8:12 AM
The time is 8:12 AM

Custom time formats

We can create additional time formats. We build a custom time format where we use time format specifiers. The following table gives a list of available format expressions.
ExpressionOutput
hthe hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hhthe hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
Hthe hour without a leading zero (0 to 23, even with AM/PM display)
HHthe hour with a leading zero (00 to 23, even with AM/PM display)
mthe minute without a leading zero (0 to 59)
mmthe minute with a leading zero (00 to 59)
sthe second without a leading zero (0 to 59)
ssthe second with a leading zero (00 to 59)
zthe milliseconds without leading zeroes (0 to 999)
zzzthe milliseconds with leading zeroes (000 to 999)
AP or A use AM/PM display. AP will be replaced by either "AM" or "PM".
ap or ause am/pm display. ap will be replaced by either "am" or "pm".
tthe timezone (for example "CEST")
Table: Time format specifiers
customtimeformats.cpp
#include <QTextStream>
#include <QTime>

int main(void)
{
   QTextStream out(stdout);

   QTime ct = QTime::currentTime();
   
   out << "The time is " << ct.toString("hh:mm:ss.zzz") << endl;
   out << "The time is " << ct.toString("h:m:s a") << endl;
   out << "The time is " << ct.toString("H:m:s A") << endl;
   out << "The time is " << ct.toString("h:m AP") << endl;  
   
   out << "The version of Qt4 is " << qVersion() << endl;
}
We have four custom time formats.
out << "The time is " << ct.toString("hh:mm:ss.zzz") << endl;
In this format, we have the hour, minute and second with a leading zero. We also add the milliseconds with leading zeroes.
out << "The time is " << ct.toString("h:m:s a") << endl;
This time format specifier uses the hour, minute and second without a leading zero and adds am/pm period identifiers.
Output
$ ./customtimeformats 
The time is 08:45:19.295
The time is 8:45:19 am
The time is 8:45:19 AM 
The time is 8:45 AM

Retrieving the weekday

The dayOfWeek() method returns a number which represents a day of a week. Where 1 is Monday and 7 is Sunday.
weekday.cpp
#include <QTextStream>
#include <QDate>

int main()
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   int wd = cd.dayOfWeek();
   
   out << "Today is " << QDate::shortDayName(wd) << endl;
   out << "Today is " << QDate::longDayName(wd) << endl;          
}
In the example we print the short and long names of a current weekday.
QDate cd = QDate::currentDate();
We get the current date.
int wd = cd.dayOfWeek();
From the current date we get the day of week.
out << "Today is " << QDate::shortDayName(wd) << endl;
With the QDate::shortDayName() static method we get the short name of the weekday.
out << "Today is " << QDate::longDayName(wd) << endl;    
Using the QDate::longDayName() static method we get the long name of the weekday.
Output
$ ./weekday 
Today is Wed
Today is Wednesday

Number of days

We can compute the number of days in a particular month using the daysInMonth() method and the number of days in a year using the daysInYear() method.
nofdays.cpp
#include <QTextStream>
#include <QDate>

int main()
{
   QTextStream out(stdout);
   
   QDate dt1(2012, 9, 18);
   QDate dt2(2012, 2, 11);
   QDate dt3(2012, 5, 1);
   QDate dt4(2012, 12, 11);
   QDate dt5(2012, 1, 21);
   
   out << "There are " << dt1.daysInMonth() << " days in " 
       << QDate::longMonthName(dt1.month()) << endl;      
   out << "There are " << dt2.daysInMonth() << " days in " 
       << QDate::longMonthName(dt2.month()) << endl;
   out << "There are " << dt3.daysInMonth() << " days in " 
       << QDate::longMonthName(dt3.month()) << endl;
   out << "There are " << dt4.daysInMonth() << " days in " 
       << QDate::longMonthName(dt4.month()) << endl;
   out << "There are " << dt5.daysInMonth() << " days in " 
       << QDate::longMonthName(dt5.month()) << endl;
     
   out << "There are " << dt1.daysInYear() << " days in year " 
       << QString::number(dt1.year()) << endl;         
}
Five date objects are created. We compute the number of days in those months and in a particular year.
QDate dt1(2012, 9, 18);
QDate dt2(2012, 2, 11);
QDate dt3(2012, 5, 1);
QDate dt4(2012, 12, 11);
QDate dt5(2012, 1, 21);
Five QDate objects are created. Each of them represents a different date.
out << "There are " << dt1.daysInMonth() << " days in " 
    << months.at(dt1.month()-1) << endl;   
We use the daysInMonth() method to get the number of days in the date object.
out << "There are " << dt1.daysInYear() << " days in year " 
    << QString::number(dt1.year()) << endl;      
And here, we get the number of days in a year using the daysInYear() method for the date object.
Output
$ ./nofdays 
There are 30 days in September
There are 29 days in February
There are 31 days in May
There are 31 days in December
There are 31 days in January
There are 366 days in year 2012

Checking validity of a date

There is a isValid() method which checks whether a date is valid or not.
isvalid.cpp
#include <QTextStream>
#include <QDate>

int main(void)
{
   QTextStream out(stdout);

   QDate dt1(2012, 5, 11);  
   QDate dt2(2012, 8, 1);
   QDate dt3(2012, 2, 30);
   
   if (dt1.isValid()) {
       out << "The first date is valid" << endl;
   } else {
       out << "The first date is not valid" << endl;
   }
   
   if (dt2.isValid()) {
       out << "The second date is valid" << endl;
   } else {
       out << "The second date is not valid" << endl;
   }
   
   if (dt3.isValid()) {
       out << "The third date is valid" << endl;
   } else {
       out << "The third date is not valid" << endl;
   }      
}
In the example we check the validity of three days.
QDate dt1(2012, 5, 11);  
QDate dt2(2012, 8, 1);
QDate dt3(2012, 2, 30);
The first two days are valid. The third one is invalid. February has 28 or 29 days.
if (dt1.isValid()) {
    out << "The first date is valid" << endl;
} else {
    out << "The first date is not valid" << endl;
}
Depending on the outcome of the isValid() method, we print a message about a validity of a date to the console.
Output
$ ./isvalid 
The first date is valid
The second date is valid
The third date is not valid

Days to, days from

We can easily calculate a date n days from a particular date. We use the addDays() method. The daysTo() method returns the number of days to a chosen date.
daystofrom.cpp
#include <QTextStream>
#include <QDate>

int main(void)
{
   QTextStream out(stdout);

   QDate dt(2012, 5, 11);  
   QDate nd = dt.addDays(55);
   
   QDate xmas(2012, 12, 24);
   
   out << "55 days from " << dt.toString() << " is " 
       << nd.toString() << endl;   
   out << "There are " << QDate::currentDate().daysTo(xmas) 
       << " days till Christmas" << endl;       
}
We get a date 55 day later from May 11, 2012. We also get the number of days till Christmas.
QDate dt(2012, 5, 11);  
QDate nd = dt.addDays(55);
The addDays() method returns a QDate which is 55 days after May 11, 2012.
QDate xmas(2012, 12, 24);
...
out << "There are " << QDate::currentDate().daysTo(xmas) 
    << " days till Christmas" << endl; 
We use the daysTo() method to calculate the number of days until Christmas.
Output
$ ./daystofrom 
55 days from Fri May 11 2012 is Thu Jul 5 2012
There are 96 till Christmas

QDateTime class

The QDateTime object contains a calendar date and a clock time. It is a combination of the QDate and QTime classes. It has many similar methods and the usage is identical to those two classes.
datetime.cpp
#include <QTextStream>
#include <QDateTime>

int main()
{
   QTextStream out(stdout);

   QDateTime cdt = QDateTime::currentDateTime();   
   
   out << "The current datetime is " << cdt.toString() << endl;
   out << "The current date is " << cdt.date().toString() << endl;
   out << "The current time is " << cdt.time().toString() << endl;   
}
The example retrieves the current datetime.
out << "The current datetime is " << cdt.toString() << endl;
This line of code prints the current datetime to the terminal.
out << "The current date is " << cdt.date().toString() << endl;
This line retrieves the date portion of the datetime object using the date() method.
Output
$ ./datetime 
The current datetime is Thu Sep 20 09:51:22 2012
The current date is Thu Sep 20 2012
The current time is 09:51:22

UTC time

Our planet is a sphere. It revolves round its axis. The Earth rotates towards the east. So the Sun rises at different times in different locations. The Earth rotates once in about 24 hours. Therefore, the world was divided into 24 time zones. In each time zone, there is a different local time. This local time is often further modified by the daylight saving.
There is a pragmatic need for one global time. One global time helps to avoid confusion about time zones and daylight saving time. The UTC (Universal Coordinated time) was chosen to be the primary time standard. UTC is used in aviation, weather forecasts, flight plans, air traffic control clearances and maps. Unlike local time, UTC does not change with a change of seasons.
utclocal.cpp
#include <QTextStream>
#include <QDateTime>

int main(void)
{
  QTextStream out(stdout);
   
  QDateTime cdt = QDateTime::currentDateTime();   
  
  out << "Universal datetime" << cdt.toUTC().toString() << endl;
  out << "Local datetime" << cdt.toLocalTime().toString() << endl;
}
In the example we compute the current datetime. We express the datetime in UTC datetime and local datetime.
out << "Universal datetime" << cdt.toUTC().toString() << endl;
The toUTC() method is used to get the UTC datetime.
out << "Local datetime" << cdt.toLocalTime().toString() << endl;
The toLocalTime() is used to get the local datetime.
Output
$ ./localutc 
Universal datetime: Thu Sep 20 09:20:34 2012
Local datetime: Thu Sep 20 11:20:34 2012
The example was run in the UTC+1 hour time zone. Plus there is a additional +1 hour for the daylight saving time.

The Unix epoch

An epoch is an instant in time chosen as the origin of a particular era. For example in western Christian countries the time epoch starts from day 0, when Jesus was born (is believed to be born). Another example is the French Republican Calendar which was used for twelve years. The epoch was the beginning of the Republican Era which was proclaimed on September 22, 1792, the day the First Republic was declared and the monarchy abolished. Computers have their epochs too. One of the most popular is the Unix time. The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601). The date and time in a computer is determined according to the number of seconds or clock ticks that have elapsed since the defined epoch for that computer or platform.
$ date +%s
1348171197
Unix date command can be used to get the Unix time. At this particular moment, 1348171197 seconds have passed since the Unix epoch.
#include <QTextStream>
#include <QDateTime>
#include <ctime>

int main()
{
  QTextStream out(stdout);

  time_t t = time(0);  
  out << t << endl;
  
  QDateTime dt;
  dt.setTime_t(t);
  out << dt.toString() << endl;
  
  QDateTime cd = QDateTime::currentDateTime();
  out << cd.toTime_t() << endl;       
}
In the example, we use two Qt4 functions to get the Unix time and convert it to the human readable form.
#include <ctime>
We include the standard C++ time header file.
time_t t = time(0);  
out << t << endl;
With the standard C++ time() command, we get the Unix time.
QDateTime dt;
dt.setTime_t(t);
out << dt.toString() << endl;
The setTime_t() method is used to convert the Unix time into the DateTime, which is formatted to human readable form.
QDateTime cd = QDateTime::currentDateTime();
out << cd.toTime_t() << endl; 
The Qt4's toTime_t() method can be also used to get the Unix time.
Output
$ ./unixepoch 
1348171451
Thu Sep 20 22:04:11 2012
1348171451
In this chapter, we have worked with time and date.

Working with strings in Qt4

In this chapter we will work with strings. Qt4 has a QString class for working with strings. It is very powerful and has numerous methods.
The QString class provides a Unicode character string. It stores a string as 16-bit QChars. Each QChar corresponds to one Unicode 4.0 character. Unlike strings in many other programming languages, a QString can be modified.

First example

In the first example, we will work with a few basic methods of the QString class.
basic.cpp
#include <QTextStream>

int main(void)
{
   QTextStream out(stdout);
   
   QString a = "love";
   
   a.append(" chess");
   a.prepend("I ");
   
   out << a << endl;
   out << "The a string has " << a.count() 
       << " characters" << endl;
       
   out << a.toUpper() << endl;    
   out << a.toLower() << endl;
   
   return 0;
}
In the code example, we initiate a QString. We append and prepend some additional text. We print the length of the string. Finally, we print the modified string in upper and lower case.
QString a = "love";
A QString is initiated.
a.append(" chess");
a.prepend("I ");
We append and prepend text to the initial string. The string is modified in-place.
out << a << endl;
'I love chess' is printed to the terminal.
out << "The a string has " << a.count() 
    << " characters" << endl;
The count() method returns the number of characters in the string. The length() and size() methods are equivalents.
out << a.toUpper() << endl;    
out << a.toLower() << endl;
These two methods return an uppercase and lowercase copy of the string. They do not modify the string, they return a new modified copy of the string.
Output
$ ./basic 
I love chess
The a string has 12 characters
I LOVE CHESS
i love chess

Initiating strings

A QString can be initiated in several ways.
init.cpp
#include <QTextStream>

int main(void)
{
   QTextStream out(stdout);
   
   QString str1 = "The night train";
   out << str1 << endl;
   
   QString str2("A yellow rose");
   out << str2 << endl;
   
   std::string s1 = "A blue sky";
   QString str3 = s1.c_str(); 
   out << str3 << endl;
   
   std::string s2 = "A thick fog";
   QString str4 = QString::fromAscii(s2.data(), s2.size());
   out << str4 << endl;
   
   char s3[] = "A deep forest";
   QString str5(s3);
   out << str5 << endl;
   
   return 0;
}
We present five ways of initiating a QString.
QString str1 = "The night train";
This is a traditional way of initiating a string in computer languages.
QString str2("A yellow rose");
This is an object way of initiating a QString.
std::string s1 = "A blue sky";
QString str3 = s1.c_str(); 
We have a string object from the C++ standard library. We use its c_str() method to generate a null-terminated sequence of characters. This array of characters, a classic C representation of a string, can be assigned to a QString variable.
std::string s2 = "A thick fog";
QString str4 = QString::fromAscii(s2.data(), s2.size());
In these code lines we convert a standard C++ string to a QString. We utilize the fromAscii() method. It takes a pointer to the an array of characters. The pointer is returned with the data() method of the std::string. The second parameter is the the size of the std::string.
char s3[] = "A deep forest";
QString str5(s3);
This is a C string. It is an array of chars. One of the QString constructors can take an array of chars as a parameter.
Output
$ ./init 
The night train
A yellow rose
A blue sky
A thick fog
A deep forest

Accessing string elements

A QString is a sequence of QChars. The elements of a string can be accessed using the [] operator or the at() method.
access.cpp
#include <QTextStream>

int main(void)
{
   QTextStream out(stdout);
   
   QString a = "Eagle";

   out << a[0] << endl;
   out << a[4] << endl;
   
   out << a.at(0) << endl;
   
   if (a.at(5).isNull()) {
     out << "Outside the range of the string" << endl;  
   }      
   
   return 0;
}
We print some individual characters from a specific QString.
out << a[0] << endl;
out << a[4] << endl;
We print the first and the fifth element of a string.
out << a.at(0) << endl;
With the at() method, we retrieve the first character of the string.
if (a.at(5).isNull()) {
    out << "Outside the range of the string" << endl;  
}      
The at() method returns null, if we are trying to access a character outside the range of string characters.
Output
$ ./access 
E
e
E
Outside the range of the string

The string length

There are three methods to get the length of a string. The size(), the count() and the length() method. All do the same thing. They return the number of characters in the specified string.
length.cpp
#include <QTextStream>

int main()
{
  QTextStream out(stdout);
   
  QString s1 = "Eagle";
  QString s2 = "Eagle\n";
  QString s3 = "Eagle ";
  QString s4 = "орел";

  out << s1.length() << endl;
  out << s2.length() << endl;
  out << s3.length() << endl;
  out << s4.length() << endl;
  
  return 0;
}
We get the size of four strings.
QString s2 = "Eagle\n";
QString s3 = "Eagle ";
Each of these two strings has a white character.
QString s4 = "орел";
This string consists of russian letters.
Output
$ ./length
5
6
6
8
From the output we can see, that the length() method counts the white characters too. The last string contains unicode letters, where each letter is stored as two characters.

String interpolation

String interpolation is a dynamic building of strings. It allows us to replace specific control characters with actual values. We use the arg() method to do the interpolation.
interpolation.cpp
#include <QTextStream>

int main()
{
   QTextStream out(stdout);
   
   QString s1 = "There are %1 white roses";
   int n = 12;
   
   out << s1.arg(n) << endl;
   
   QString s2 = "The tree is %1m high";
   double h = 5.65;
   
   out << s2.arg(h) << endl;
   
   QString s3 = "We have %1 lemons and %2 oranges";
   int ln = 12;
   int on = 4;
   
   out << s3.arg(ln).arg(on) << endl;
   
   return 0;
}
The markers which are going to be replaced begin with the % character. The following character is a number specifying the argument. There can be multiple of arguments for a string. The arg() method is overloaded, it can take integers, long numbers, chars, QChars among others.
QString s1 = "There are %1 white roses";
int n = 12;
The %1 is the marker which we plan to replace. We have defined one integer.
out << s1.arg(n) << endl;
The arg() method takes an integer. The %1 marker is replaced with the value of the n variable.
QString s2 = "The tree is %1m high";
double h = 5.65;

out << s2.arg(h) << endl;
These three lines do the same thing for a double number. The correct arg() method is called automatically.
QString s3 = "We have %1 lemons and %2 oranges";
int ln = 12;
int on = 4;

out << s3.arg(ln).arg(on) << endl;
We can have multiple control characters. The %1 refers to the first argument, the %2 to the second. The arg() methods are called in a consecutive chain.
Output
$ ./interpolation 
There are 12 white roses
The tree is 5.65m high
We have 12 lemons and 4 oranges

Substrings

When doing text processing, we need to find substrings of normal strings. We have left(), mid() and right() methods at our disposal.
substrings.cpp
#include <QTextStream>

int main(void)
{
   QTextStream out(stdout);
   
   QString str = "The night train";
   
   out << str.right(5) << endl;
   out << str.left(9) << endl;
   out << str.mid(4, 5) << endl;
   
   QString str2("The big apple");
   QStringRef sub(&str2, 0, 7);
   
   out << sub.toString() << endl;
   
   return 0;
}
We will use all three methods to find some substrings of a given string.
out << str.right(5) << endl;
With the right() method, we get the 5 rightmost characters of the str string. The 'train' is printed.
out << str.left(9) << endl;
With the left() method, we get the 9 leftmost characters of the str string. The 'The night' is printed.
out << str.mid(4, 5) << endl;
With the mid() method, we get 5 characters starting from position 4. The 'night' is printed.
QString str2("The big apple");
QStringRef sub(&str2, 0, 7);
The QStringRef class is a read-only version of a QString. Here we create a QStringRef of a portion of the str2 string. The second parameter is the position and the third is the length of the substring.
Output
$ ./substrings 
train
The night
night
The big

Looping through strings

A QString consists of QChars. We can loop through the QString to access each element of a string.
looping.cpp
#include <QTextStream>

int main(void)
{
  QTextStream out(stdout);
   
  QString str = "There are many stars.";
  
  foreach (QChar qc, str) {
    out << qc << " ";  
  }
  
  out << endl;
  
  for (QChar *it=str.begin(); it!=str.end(); ++it) {
    out << *it << " " ;
  }
  
  out << endl;
  
  for (int i = 0; i < str.size(); ++i) {
    out << str.at(i) << " ";    
  }
  
  out << endl;
  
  return 0;
}
We show three ways to go through a QString. We add a space character between the letters as we print them to the terminal.
foreach (QChar qc, str) {
  out << qc << " ";  
}
The foreach keyword is a Qt extension to the C++ language. The first parameter of the keyword is the string element, the second one is the string.
for (QChar *it=str.begin(); it!=str.end(); ++it) {
  out << *it << " " ;
}
In this code, we use iterators to go through the string.
for (int i = 0; i < str.size(); ++i) {
  out << str.at(i) << " ";    
}
We compute the size of the string and use the at() method to access the string elements.
Output
$ ./looping
T h e r e   a r e   m a n y   s t a r s . 
T h e r e   a r e   m a n y   s t a r s . 
T h e r e   a r e   m a n y   s t a r s . 

String comparison

The QString::compare() static method is used to compare two strings. The method returns an integer. If the returned value is less than zero, the first string is less than the second. If it returns zero, both strings are equal. Finally, if the returned value is greater than zero, the first string is greater than the second. By 'less' we mean that a specific character of a string is positioned before the other one in the character table. Strings are compared the following way. The first characters of the two strings are compared. If they are equal, the following two characters are compared. Until we find some characters that differ or we find that all characters match.
comparing.cpp
#include <QTextStream>

#define STR_EQUAL 0

int main(void)
{
   QTextStream out(stdout);
   
   QString a = "Rain";
   QString b = "rain";
   QString c = "rain\n";
   
   if (QString::compare(a, b) == STR_EQUAL) {
     out << "a, b are equal" << endl;
   } else {
     out << "a, b are not equal" << endl;
   }
   
   out << "In case insensitive comparison:" << endl;
   
   if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
     out << "a, b are equal" << endl;
   } else {
     out << "a, b are not equal" << endl;
   }     
   
   if (QString::compare(b, c) == STR_EQUAL) {
     out << "b, c are equal" << endl;
   } else {
     out << "b, c are not equal" << endl;
   }   

   c.chop(1);
   
   out << "After removing the new line character" << endl;
   
   if (QString::compare(b, c) == STR_EQUAL) {
     out << "b, c are equal" << endl;
   } else {
     out << "b, c are not equal" << endl;
   }            
   
   return 0;
}
We will do case sensitive and case insensitive comparison with the compare() method.
#define STR_EQUAL 0
For better code clarity, we define the STR_EQUAL constant.
QString a = "Rain";
QString b = "rain";
QString c = "rain\n";
We will be comparing these three strings.
if (QString::compare(a, b) == STR_EQUAL) {
    out << "a, b are equal" << endl;
} else {
    out << "a, b are not equal" << endl;
}
We compare the a and b strings. The strings are not equal. They differ in the first character.
if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
    out << "a, b are equal" << endl;
} else {
    out << "a, b are not equal" << endl;
}     
In case of case insensitive comparison, the strings are equal. The Qt::CaseInsensitive makes the comparison case insensitive.
c.chop(1);
The chop() method removes the last character from the c string. Now the b, c strings are equal.
Output
$ ./comparing 
a, b are not equal
In case insensitive comparison:
a, b are equal
b, c are not equal
After removing the new line character
b, c are equal

Converting strings

Strings often need to be converted to other data types. And vice versa. The toInt(), toFloat(), toLong() are three QString methods which convert a string to an integer, float and long number. (There are more such methods.) The setNum() method converts various numeric data types to a string. The method is overloaded and the correct one is called automatically.
Output
#include <QTextStream>

int main(void)
{
  QTextStream out(stdout);
   
  QString s1 = "12";
  QString s2 = "15";
  QString s3, s4;
  
  out << s1.toInt() + s2.toInt() << endl;
   
  int n1 = 30;
  int n2 = 40;
  
  out << s3.setNum(n1) + s4.setNum(n2) << endl;
   
  return 0;
}
In the example we convert two strings to integers and add them. Then we convert two integers to strings and concatenate them.
out << s1.toInt() + s2.toInt() << endl;
The toInt() method converts a string to an integer. We add two numbers converted froms strings.
out << s3.setNum(n1) + s4.setNum(n2) << endl; 
In this case the setNum() method converts an integer to a string. We concatenate two strings.
Output
$ ./converts 
27
3040

Letters

Characters are divided into various categories. Digits, letters, spaces or punctuation characters. Each QString consists of QChars. The QChar has the isDigit(), isLetter(), isSpace() and isPunct() method to perform the job.
letters.cpp
#include <QTextStream>

int main(void)
{
  QTextStream out(stdout);
   
  int digits  = 0;
  int letters = 0;
  int spaces  = 0;
  int puncts  = 0;
  
  QString str = "7 white, 3 red roses.";
  
  foreach(QChar s, str)
  {
    if (s.isDigit()) {
      digits++;
    } else if (s.isLetter()) {
      letters++;
    } else if (s.isSpace()) {
      spaces++;
    } else if (s.isPunct()) {
      puncts++;
    }    
  }  
  
  out << QString("There are %1 characters").arg(str.count()) << endl;
  out << QString("There are %1 letters").arg(letters) << endl;
  out << QString("There are %1 digits").arg(digits) << endl;
  out << QString("There are %1 spaces").arg(spaces) << endl;
  out << QString("There are %1 punctuation characters").arg(puncts) << endl;
    
  return 0;
}
In the example we define a simple sentence. We will count the number of digits, letters, spaces and punctuation characters in the sentence.
int digits  = 0;
int letters = 0;
int spaces  = 0;
int puncts  = 0;
We define an integer variable for each character category.
QString str = "7 white, 3 red roses.";
This is the sentence to be examined.
foreach(QChar s, str)
{
  if (s.isDigit()) {
    digits++;
} else if (s.isLetter()) {
    letters++;
} else if (s.isSpace()) {
    spaces++;
} else if (s.isPunct()) {
    puncts++;
  }    
}  
We use the foreach keyword to go through the QString. Each of the elements is a QChar. We use the methods of the QChar class to determine the categories of characters.
out << QString("There are %1 characters").arg(str.count()) << endl;
out << QString("There are %1 letters").arg(letters) << endl;
out << QString("There are %1 digits").arg(digits) << endl;
out << QString("There are %1 spaces").arg(spaces) << endl;
out << QString("There are %1 punctuation characters").arg(puncts) << endl;
Using the string interpolation, we print the numbers to the terminal.
Output
$ ./letters 
There are 21 characters
There are 13 letters
There are 2 digits
There are 4 spaces
There are 2 punctuation characters

Modifying strings

Some methods (for example toLower() method) return a new modified copy of an original string. Other methods modify the string in-place. We will present some of them.
modify.cpp
#include <QTextStream>

int main(void)
{
   QTextStream out(stdout);
   
   QString str = "Lovely";   
   str.append(" season");
   
   out << str << endl;
   
   str.remove(10, 3);
   out << str << endl;

   str.replace(7, 3, "girl");
   out << str << endl;
   
   str.clear();
   
   if (str.isEmpty()) {
     out << "The string is empty" << endl;
   }
   
   return 0;
}
We describe four methods that modify a string in-place.
str.append(" season");
The append() method adds a new string at the end of the string.
str.remove(10, 3);
The remove() method removes 3 characters from the string, starting from position 10.
str.replace(7, 3, "girl");
The replace() method replaces 3 characters beginning at position 7 with the specified string.
str.clear();
The clear() method clears the string.
Output
$ ./modify 
Lovely season
Lovely sea
Lovely girl
The string is empty
In this chapter, we have worked with strings in Qt4.

Qt4 utility classes

In this part of the Qt4 C++ programming tutorial, we will talk about the utility classes available in the Qt4 library.
The Qt4 library consists of a large group of helper classes, that help programmers to do their job. These include classes for working with strings, files, XML files, streams, database or network. Here we will show only a tiny drop of the whole lake.
The Qt4 library can be used to create console and GUI applications. In this chapter, we will illustrate some of the helper classes in console based applications.

Printing text to the console

This is a simple console application. The application puts some text into the console window.
console.cpp
#include <iostream>

int main()
{
  std::cout << "console application\n";
}
In the first example, we print the text using the STL (Standard Template Library) library.
console2.cpp
#include <QTextStream>

int main()
{
   QTextStream out(stdout);
   out << "console application\n";
}
The second example shows, how we can print text using the Qt4 programming library.
Output
console application

QFile

The QFile is a class for reading from and writing to files.
In the first example, we write a sentence to a file.
file.cpp
#include <QTextStream>
#include <QFile>

int main()
{

   QFile data("myfile");

   if (data.open(QFile::WriteOnly)) {
     QTextStream out(&data);
     out << "You make me want to be a better man." << endl;
   }
}
Output
$ cat myfile 
You make me want to be a better man.
The next example, we print the contents of a file to the console. The text will be in Hungarian language, so we must set the correct codec.
szerelem
S a régi szeretőmér­
mit nem cselekednék,
tengerből a vizet
kanállal lemerném.

S a tenger fenekéről
apró gyöngyöt szednék,
s a régi szeretőmnek
gyöngykoszorút kötnék. 
szerelem.cpp
#include <QTextStream>
#include <QFile>

int main()
{
  QFile data("szerelem");

  QString line;

  if (data.open(QFile::ReadOnly)) {
    QTextStream in(&data);
    QTextStream out(stdout);

    out.setCodec("UTF-8");
    in.setCodec("UTF-8");

    do {
      line = in.readLine();
      out << line << endl;
    } while (!line.isNull());
  }
}
Output
 S a régi szeretőmér­
mit nem cselekednék,
tengerből a vizet
kanállal lemerném.

S a tenger fenekéről
apró gyöngyöt szednék,
s a régi szeretőmnek
gyöngykoszorút kötnék. 

QList

The QList is one of the generic Qt4's containers. It is used to store a list of values and provides fast index-based access as well as fast insertions and removals.
mlist.cpp
#include <QTextStream>
#include <QList>

int main()
{
  QTextStream out(stdout);

  QList<QString> list;

  list << "Balzac" << "Tolstoy" << "Guldbrassen"
       << "London" << "Galsworthy" << "Sienkiewicz";

  qSort(list);

  for (int i = 0; i < list.size(); ++i) {
    out << list.at(i) << endl;
  }

}
In the code example, we create a list of great novelists. We sort alphabetically the list and print it to the console.
Output
Balzac
Galsworthy
Guldbrassen
London
Sienkiewicz
Tolstoy

QDir

The QDir class provides access to directory structures and their contents.
home.cpp
#include <QTextStream>
#include <QDir>

int main()
{
  QTextStream out(stdout);
  QString home = QDir::homePath();
  out << home << endl;
}
This example determines the home directory and prints it to the console.
Output
/home/vronskij
In the following example, we use the QDir class
filters.cpp
#include <QTextStream>
#include <QDir>


int main()
{
  QTextStream out(stdout);
  QDir dir;

  QStringList filters;
  filters << "*.c" << "*.c~";
  dir.setNameFilters(filters);

  QFileInfoList list = dir.entryInfoList();

  for (int i = 0; i < list.size(); ++i) {
    QFileInfo fileInfo = list.at(i);
    out << QString("%1").arg(fileInfo.fileName());
    out << endl;
  } 
}
The code example determines all files in the current directory and applies a specific filter to the files.
Output
$ ls -F
anim*  anim.c  anim.c~  filters*
$ ./filters 
anim.c
anim.c~

QTime

The QTime class provides clock time functions.
In the following example, we print the current local time to the console.
mtime.cpp
#include <QTextStream>
#include <QTime>

int main()
{
   QTextStream out(stdout);

   QTime qtime = QTime::currentTime();
   QString stime = qtime.toString(Qt::LocalDate);

   out << stime << endl;
}
Watch out that the file must not be called time.cpp.
Output
$ ./time 
10:30:33 PM

QString

The QString class is used to work with strings. This is probably the most important utility class available in Qt4 programming library.
concat.cpp
#include <QTextStream>

int main()
{
   QString a = "Disziplin ";
   QString b = "ist ";
   QString c = "Macht.\n";

   QTextStream out(stdout);
   out << a + b + c;
}
The first example concatenates three strings.
Output
$ ./concat
Disziplin ist Macht.
The seconds example builds a string by means of appending text one after the other.
append.cpp
#include <QTextStream>

int main()
{

   QString string = "Whether I shall ";

   string.append("turn out to be the hero of my own life, \n");
   string.append("or whether that station will be held by anybody else, \n");
   string.append("these pages must show.\n");

   QTextStream out(stdout);
   out << string;
}
Output
$ ./append
Whether I shall turn out to be the hero of my own life, 
or whether that station will be held by anybody else, 
these pages must show.
The next example shows an argument substitution.
arg.cpp
#include <QTextStream>

int main()
{
   QString string = "What if I gave you %1 red roses?";
   int num = 21;

   QTextStream out(stdout);
   out << string.arg(num) << endl; 
}
Output
$ ./str3 
What if I gave you 21 red roses?
The following example shows, how we can determine the size of the string.
size.cpp
#include <QTextStream>

int main()
{
 QString string = "The history of my life.";

 QTextStream out(stdout);
 out << "The string has " + QString::number(string.size())
    + " characters." << endl; 
}
Output
 ./size
The string has 23 characters.
The last example is about making a string uppercase or lowercase.
uplow.cpp
#include <QTextStream>

int main()
{
  QString string = "The history of my life.";

  QTextStream out(stdout);
  out << string.toLower() << endl; 
  out << string.toUpper() << endl; 
}
Output
$ ./uplow
the history of my life.
THE HISTORY OF MY LIFE.
In this chapter, we have described some utility classes in Qt4.

Introduction to Qt4 toolkit

In this part of the Qt4 tutorial, we will introduce the Qt4 library. We will install the Qt4 library and create our first small Qt4 application.

Qt Development Frameworks

Qt toolkit was initially developed by Trolltech, a Norwegian software company. In 2008 the company was acquired by Nokia. The company was renamed to Qt Development Frameworks. In August 2012 a Finnish development company Digia acquired Qt software technologies from Nokia. Meanwhile a Qt Project was created in which the development of open source Qt continues. The website for the open source Qt toolkit can be found at qt-project.org.

Qt toolkit

Qt is a cross-platform application development framework. Some of the well known applications developed with Qt are KDE, Opera, Google Earth, Skype, VLC, Maya or Mathematica. Qt was first publicly released on May 1995. It is dual licensed. It can be used for creating open source applications as well as commercial ones. Qt toolkit is a very powerful toolkit. It is well established in the open source community. Thousands of open source developers use Qt all over the world.

Download

We go to the download page. We can have either an online or offline installation. It is possible to choose to download the whole Qt4 SDK or get the parts of the SDK separatly. The complete SDK has some additional development tools. These can be also downloaded later. In this page we will show how to install Qt libraries 4.8.3 for Linux.
$ ls qt-everywhere-opensource-src-4.8.3.tar.gz 
qt-everywhere-opensource-src-4.8.3.tar.gz
From the download page we download the Qt4 libraries.
$ tar -xzvf qt-everywhere-opensource-src-4.8.3.tar.gz 
The command will decompress all the files to a directory qt-everywhere-opensource-src-4.8.3.
$ du -hs qt-everywhere-opensource-src-4.8.3
685M    qt-everywhere-opensource-src-4.8.3
The size of the directory is now 685 MB.
$ cd qt-everywhere-opensource-src-4.8.3/
We go to the created directory. Now it is time to carefully read the README and the INSTALL file. There we will find detailed installation instructions. The installation is easy and straightforward.

Install

We install the library the classic way. On Unix systems, installation of a software is divided into three steps.
  • Configuration
  • Building
  • Installation
$ ./configure -prefix /usr/local/qt4
Which edition of Qt do you want to use ?

Type 'c' if you want to use the Commercial Edition.
Type 'o' if you want to use the Open Source Edition.
First we run the configure script. The script will ask whether we want the commercial or open source edition of the Qt4 library. The script will configure the library for our machine type. By default, the qt will be installed in /usr/local/Trolltech/Qt-4.8.3 directory. This can be changed by the -prefix parameter of the configure script. We install the library into the /usr/local/qt4 directory. Note that the installation word has two meanings here. It is the whole process consisting of all three steps. And it also means 'moving files to specific directories', which is the last, third step.
This is the  Open Source Edition.

You are licensed to use this software under the terms of
the Lesser GNU General Public License (LGPL) versions 2.1.
You are also licensed to use this software under the terms of
the GNU General Public License (GPL) versions 3.

Type '3' to view the GNU General Public License version 3.
Type 'L' to view the Lesser GNU General Public License version 2.1.
Type 'yes' to accept this license offer.
Type 'no' to decline this license offer.

Do you accept the terms of either license? yes
Confirming licence agreement.
Qt is now configured for building. Just run 'make'.
Once everything is built, you must run 'make install'.
Qt will be installed into /usr/local/qt4

To reconfigure, run 'make confclean' and 'configure'.
We get this message after the configure script finishes.
$ make
We use the make command to start the build process. The building of the Qt toolkit can take several hours. It depends on the power of your processor.
The last step is installing, or moving files to the directories.
sudo make install
This command finishes the installation process. The library is now installed in /usr/local/qt4 directory.
$ du -sh /usr/local/qt4
435M    /usr/local/qt4
The size of the directory is 435 MB. As we can see, Qt is a huge library.
The last thing that we do, is adding the qt4 path to the PATH system variable. The bash users, need to edit the either the .profile file or the .bashrc file.
PATH=/usr/local/qt4/bin:$PATH
export PATH
We have added a path to the bin directory of the Qt4 library to the PATH environment variable. The changes will be active after another login.

Testing a small example

Finally we will write a small code example.
#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;

    window.resize(250, 150);
    window.setWindowTitle("Simple example");
    window.show();

    return app.exec();
}
To build this example, we will use a very handy tool called qmake.
qmake -project
qmake
make
If the qt4 installation directory is not a part of the PATH variable, we can provide the full path to the qmake tool.
/usr/local/qt4/bin/qmake -project
/usr/local/qt4/bin/qmake
make
Simple example
Figure: Simple example
Installation finished OK.
This chapter was an introduction to the Qt4 library.