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

From KDE TechBase
Revision as of 15:21, 2 July 2011 by Aspotashev (talk | contribs) (Created page with "В каждом графическом приложении на Qt должен быть создан ровно один объект класса [http://doc.qt.nokia.com/late...")
Other languages:


Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01


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

Здравствуй, мир!

Файлы:

Обзор

Этот первый пример — программа «Hello world!» («Здравствуй, мир!»). Здесь содержатся минимальные знания, необходимые для написания работоспособного приложения на Qt. Выше приведён снимок экрана программы.

Исходный код приложения:

require 'Qt4'

app = Qt::Application.new(ARGV)

hello = Qt::PushButton.new('Hello World!')
hello.resize(100, 30)
hello.show()

app.exec()

Введение

Главный файл в приложении на QtRuby обычно занимается только инициализацией, после чего передаёт управление библиотеке Qt, которая потом сообщает программе о действиях пользователя через события.

В каждом графическом приложении на Qt должен быть создан ровно один объект класса Qt::Application. Этот объект управляет глобальными для приложения параметрами, такими как шрифт и форма курсора мыши по умолчанию.

Qt::PushButton is a GUI push button that the user can press and release. It manages its own look and feel, like every other Qt::Widget. A widget is a user interface object that can process user input and draw graphics. The programmer can change both the overall look and feel and many minor properties of it (such as color), as well as the widget's content. A Qt::PushButton can show either text or a Qt::Icon.

Line by Line Walkthrough

require 'Qt4'

This line loads the QtRuby extension.

app = Qt::Application.new(ARGV)

app is this program's Qt::Application instance. It is created here. We pass ARGV to the Qt::Application constructor so that it can process certain standard command-line arguments (such as -display under X11). All command-line arguments recognized by Qt are removed from ARGV.

Note: It is essential that the Qt::Application object be created before any window-system parts of Qt are used.

hello = Qt::PushButton.new('Hello World!')

Here, after the Qt::Application, comes the first window-system code: A push button is created.

The button is set up to display the text "Hello world!". Because we don't specify a parent window (as second argument to the Qt::PushButton constructor), the button will be a window of its own, with its own window frame and title bar.

hello.resize(100, 30)

The button is set up to be 100 pixels wide and 30 pixels high (excluding the window frame, which is provided by the windowing system). We could call Qt::Widget::move() to assign a specific screen position to the widget, but instead we let the windowing system choose a position.

hello.show()

A widget is never visible when you create it. You must call Qt::Widget::show() to make it visible.

app.exec()

This is where our program passes control to Qt. Qt::CoreApplication::exec() will return when the application exits. (Qt::CoreApplication is Qt::Application's base class. It implements Qt::Application's core, non-GUI functionality and can be used when developing non-GUI applications.)

In Qt::CoreApplication::exec(), Qt receives and processes user and system events and passes these on to the appropriate widgets.

You should now try to run this program.

Running the Application

When you run the application, you will see a small window filled with a single button, and on it you can read the famous words: "Hello world!"

Exercises

Try to resize the window. Click the button. If you're running X11, try running the program with the -geometry option (for example, -geometry 100x200+10+20).