Разработка/Руководства/Введение в Qt4 на Ruby/Глава 3

From KDE TechBase
Revision as of 17:06, 2 July 2011 by Aspotashev (talk | contribs) (Created page with "Виджет, который не встроен в родительский виджет (как в нашем примере) называется окном. Обычно ок...")
Other languages:


Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3


Иерархия виджетов
Серия примеров   Введение в программирование на Qt®4 на языке Ruby
Необходимо знать   Пример 2: Выход по нажатию
Следующий пример   Пример 4: Давайте создадим свой виджет
Литература   нет

Иерархия виджетов

Файлы:

Обзор

Этот пример показывает, как можно создать родительский и дочерний виджеты.

Мы максимально упростим задачу и создадим единственный родительский виджет и только один дочерний ему виджет.

require 'Qt4'

app = Qt::Application.new(ARGV)

window = Qt::Widget.new()
window.resize(200, 120)

quit = Qt::PushButton.new('Quit', window)
quit.font = Qt::Font.new('Times', 18, Qt::Font::Bold)
quit.setGeometry(10, 40, 180, 40)
Qt::Object.connect(quit, SIGNAL('clicked()'), app, SLOT('quit()'))

window.show()
app.exec()

Построчный обзор программы

window = Qt::Widget.new()

Здесь мы создаём объект простого виджета. Qt::Widget — базовый класс для всех объектов интерфейса пользователя. Виджет — это неделимая единица интерфейса. Он получает события от оконной системы при использовании мыши, клавиатуры и других действиях, а также рисует себя на экране. Область виджета на экране может быть обрезана родительским виджетом или перекрыта виджетами, расположенными поверх него.

Виджет, который не встроен в родительский виджет (как в нашем примере) называется окном. Обычно окна имеют рамку и соответствующий элемент в панели задач, которые создаются оконной системой. Виджет, не имеющий родительского виджета, всегда является свободным окном. Его исходное положение на экране выбирается оконной системой.

window.resize(200, 120)

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

quit = Qt::PushButton.new('Quit', window)

A child is born. This Qt::PushButton is created with a parent widget (window). A child widget is always displayed within its parent's area. When displayed, it is clipped by its parent's bounds. By default, it is rooted at the top-left corner of its parent, at position (0, 0).

quit.setGeometry(10, 40, 180, 40)

The Qt::Widget::setGeometry() function takes four arguments: The first two arguments are the x and y coordinates of the button's top-left corner. The coordinates are relative to the parent widget. The last two arguments are the button's width and height. The result is a button that extends from position (10, 40) to position (190, 80).

window.show()

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

Running the Application

The button no longer fills the entire window. Instead, it stays at position (10, 40) within the window and with a size of (180, 40), because of the Qt::Widget::setGeometry() call.

Exercises

Try resizing the window. How does the button change? 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?