HomeHome

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>
#include <qvbox.h>

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

    QVBox box;
    box.resize( 200, 120 );

    QPushButton quit( "Quit", &box );
    quit.setFont( QFont( "Times", 18, QFont::Bold ) );

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

    a.setMainWidget( &box );
    box.show();

    return a.exec();
}

Line by Line Walk-Through

    #include <qvbox.h>

We add an include of qvbox.h, to get the layout class we'll use.

        QVBox box;

Here we simply create a vertical box container. The QVBox arranges its child widgets in a vertical row, one above the other, handing out space according to each child's QWidget::sizePolicy().

        box.resize( 200, 120 );

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

        QPushButton quit( "Quit", &box );

A child is born.

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

The mother widget, the QVBox, automatically adds the child, centered in its box. Since nothing else is added, the button gets all the space the mother has.

        box.show();

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

Behavior

The button no longer fills the entire widget. Instead, it gets a "natural" size. This is because there is now a new top-level widget, which uses layout management to set a good size and position for the button.

Excercises

Try resizing the window. How does the button change? What is the button's size change policy? What happens if you try to make the window really small?

You may now go on to chapter four.

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


Copyright © 2000 TrolltechTrademarks
Qt version 2.2.1