O'Reilly logo

Programming with Qt, 2nd Edition by Matthias Kalle Dalheimer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required