Chapter 2. First Steps in Qt Programming

The time has come to start getting our hands dirty with some real code. Of course, our first program will be the traditional “Hello, world” exercise. We’ll then gradually build from there to create a small, but complete, paint program. The topics in this chapter are important building blocks for almost every Qt programming task, so make sure you understand them.

Hello, world!

This program, which creates a little window with “Hello, world” in it, is very simple. It contains code (see Example 2-1) that you will see often in Qt programs.[5]

Example 2-1. helloworld.cpp: Hello, world in Qt
#include <qapplication.h>
#include <qlabel.h>

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

  QLabel* mylabel = new QLabel( "Hello, world", 0 );
  mylabel->resize( 120, 30 );

  myapp.setMainWidget( mylabel );
  mylabel->show();
  return myapp.exec();
}

Let’s go through this code line by line. The first two lines include Qt header files. For most cases, a one-to-one relationship exists between Qt classes and Qt header files. The header file names are almost always the same as the class names, with all letters in lowercase and the conventional .h appended to each name. In some rare cases, several classes are grouped together in one header file. For example, you can find both the class declarations of QListView and QListViewItem in qlistview.h.[6] When in doubt, check the documentation. Shortly, we’ll cover how the Qt reference documentation ...

Get Programming with Qt, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.