Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

[Previous: Chapter 2] [Qt Tutorial] [Next: Chapter 4]

# Qt Tutorial 3 - Family Values

Files:

- tutorial/t3/main.cpp

This example shows how to create parent and child widgets.

We'll keep it simple and use just a single parent and a lone child.

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

        #include <QApplication>
        #include <QFont>
        #include <QPushButton>
        #include <QVBoxWidget>

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

            QVBoxWidget vbox;
            vbox.resize(200, 120);

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

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

            app.setMainWidget(&vbox);
            vbox.show();
            return app.exec();
        }

## Line by Line Walkthrough

        #include <QVBoxWidget>

We add an include of <QVBoxWidget> to get the layout class we'll use.

            QVBoxWidget vbox;

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

            vbox.resize(200, 120);

We set the widget's width to 200 pixels and the height to 120 pixels.

            QPushButton quit("Quit", &vbox);

A child is born.

This QPushButton is created with a parent widget (`vbox`). A child widget is always displayed within its parent's area. When displayed, it is clipped by its parent's bounds.

The parent widget, the QVBoxWidget, automatically adds the child centered in its box. Because nothing else is added, the button gets all the space the parent has. Since the QVBoxWidget has no parent, it is a top-level window, with its own window frame and taskbar entry.

            vbox.show();

When a parent widget is shown, it will call show for all its children (except those that were explicitly hidden using QWidget::hide()).

## Running the Application

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 the button's size hint and size change policy to set the button's size and position. (See QWidget::sizeHint() and QWidget::setSizePolicy() for more information about these functions.)

## Exercises

Try resizing the window. How does the button change? What is the button's size-change policy? What happens to the button's height if you run the program with a bigger font? What happens if you try to make the window really small?

[Previous: Chapter 2] [Qt Tutorial] [Next: Chapter 4]