Qt logo


Chapter 2: Calling it Quits


Screenshot of tutorial two

Having created a window in chapter one, we will now go on to make the application quit properly when the user tells it to.

We will also use a font that is more exciting than the default one.

/****************************************************************
**
** Qt tutorial 2
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qfont.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    QPushButton quit( "Quit" );
    quit.resize( 75, 30 );
    quit.setFont( QFont( "Times", 18, QFont::Bold ) );

    QObject::connect( &quit, SIGNAL(clicked()), &a, SLOT(quit()) );

    a.setMainWidget( &quit );
    quit.show();
    return a.exec();
}

Line by Line Walk-Through

    #include <qfont.h>

Since this program uses QFont, it needs to include qfont.h. Qt's font abstraction is rather different from the horror provided by X, and loading and using fonts has been highly optimized.

        QPushButton quit( "Quit" );

This time, the button says "Quit" and that's exactly what the program will do when the user clicks the button. This is not a coincidence.

        quit.resize( 75, 30 );

We've chosen another size for the button since the text is a bit shorter than "Hello World!". We could also have used QPushButton::setAutoResize(), or even use QFontMetrics to set right size.

        quit.setFont( QFont( "Times", 18, QFont::Bold ) );

Here we choose a new font for the button, an 18-point bold font from the Times family. Note that we create the font on the spot.

It is also possible to change the default font for the whole application.

        QObject::connect( &quit, SIGNAL(clicked()), &a, SLOT(quit()) );

connect() is perhaps the most central feature of Qt. Note that connect() is a static function in QObject. Do not confuse it with the connect() function in the socket library.

This line establishes a one-way connection between two Qt objects (objects that inherit QObject, directly or indirectly). Every Qt object can have both signals (to send messages) and slots (to receive messages). All widgets are Qt objects. They inherit QWidget which in turn inherits QObject.

Here, the clicked() signal of quit is connected to the quit() slot of a, so that when the button is clicked, the application quits.

The Signals and Slots documentation describes this topic in detail.

Behavior

When you run this program, you will see an even smaller window than in chapter one, filled with an even smaller button.

Excercises

Try to resize the window. Press the button. Oops! That connect() would seem to make some difference :)

Are there any other signals in QPushButton you can connect to quit? Hint: The QPushButton inherits most of its behavior from QButton.

You may now go on to chapter three.

[Previous tutorial] [Next tutorial] [Main tutorial page]


Copyright © 1998 Troll TechTrademarks
Qt version 1.42