Qt logo


Chapter 3: Family Values


Screenshot of tutorial three

This example shows how to create mother and child widgets.

We'll keep it simple and use just a single mother (uh, family values?) and a lone child.

/****************************************************************
**
** Qt tutorial 3
**
****************************************************************/

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

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

    QWidget w;
    w.resize( 200, 120 );

    QPushButton quit( "Quit", &w );
    quit.move( 62, 40 );
    quit.resize( 75, 30 );
    quit.setFont( QFont( "Times", 18, QFont::Bold ) );

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

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

Line by Line Walk-Through

        QWidget w;

Here we simply create a widget. Note that we did not have to include qwidget.h, because we have included qpushbutton.h and QPushButton is a subclass of QWidget (see Class Hierarchy).

A QWidget does not handle any events, it simply displays itself using its background color and caption.

        w.resize( 200, 120 );

We set the width to 200 pixels and the height to 120 pixels.

        QPushButton quit( "Quit", &w );

A child is born.

This QPushButton is created with both a text, "Quit", and a mother, w. A child widget is always on top of its mother. When displayed, it is clipped by its mother's bounds.

        quit.move( 62, 40 );

The child is moved to a position of 62,40, relative to its mother's top left corner (excluding the window frame). The coordinate is as usual for a visual display, x increases to the right and y increases downwards.

        w.show();

When a widget is shown, it will call show for all its children (except those you have done an explicit hide() on).

Behavior

Note that if you resize the widget, the button is not resized, unlike the programs in the first two chapters. That's because the top level widget is a QWidget, which does not react to resizing.

If you're using X11, you will see the same effect if you invoke the program with -geometry.

Excercises

Try changing the arguments to quit.move() and/or quit.resize(). What happens if quit is partly "outside" w?

For X11 users:

Also try moving the w.resize() to after the quit.move/resize, and to after a.setMainWidget(). Does -geometry still work?

You may now go on to chapter four.

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


Copyright © 1998 Troll TechTrademarks
Qt version 1.42