Home

Qt Tutorial - Chapter 3: Family Values

Screenshot of tutorial three

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
#**
#****************************************************************

require 'Qt'

a = Qt::Application.new(ARGV)

box = Qt::VBox.new()
box.resize(200, 120)

quit = Qt::PushButton.new('Quit', box)
quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))

a.connect(quit, SIGNAL('clicked()'), SLOT('quit()'))

a.setMainWidget(box)
box.show

a.exec
exit

Line-by-line Walkthrough

        box = Qt::VBox.new()

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

        box.resize( 200, 120 )

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

        quit = Qt::PushButton.new( "Quit", box )

A child is born.

This Qt::PushButton is created with both a text ("Quit") and a parent (box). A child widget is always on top of its parent. When displayed, it is clipped by its parent's bounds.

The parent widget, the Qt::VBox, automatically adds the child centered in its box. Because nothing else is added, the button gets all the space the parent has.

        box.show()

When a parent widget is shown, it will call show for all its children (except those on which you have done an explicit Qt::Widget.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 the button's size hint and size change policy to set the button's size and position. (See Qt::Widget.sizeHint() and Qt::Widget.setSizePolicy() for more information about these methods.)

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?

You're now ready for Chapter 4.

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


Copyright © 2004 TrolltechTrademarks
Qt 3.3.3