Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2/ru: Difference between revisions

From KDE TechBase
(Created page with "Пример 3: Иерархия виджетов")
(Updating to match new version of source page)
 
(19 intermediate revisions by one other user not shown)
Line 1: Line 1:
<languages />
<languages />
{{Template:I18n/Language Navigation Bar|Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2}}


{{TutorialBrowser/ru|
{{TutorialBrowser/ru|
Line 10: Line 8:
}}
}}


== Calling it Quits ==
== Выход по нажатию ==
[[Image:Qt4_Ruby_Tutorial_Screenshot_2.png|center]]
[[Image:Qt4_Ruby_Tutorial_Screenshot_2.png|center]]


Files:
Файлы:
* [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t2/t2.rb t2.rb]
* [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t2/t2.rb t2.rb]


=== Overview ===
=== Обзор ===


Having created a window in Chapter 1, we will now go on to make the application quit properly when the user tells it to.
Уже создав окно в первой главе, мы заставим приложение корректно завершаться по нажатию кнопки.


We will also use a font that is more exciting than the default one.
Кроме того, мы научимся менять шрифт.


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
Line 37: Line 35:
</syntaxhighlight>
</syntaxhighlight>


=== Line by Line Walkthrough ===
=== Построчный обзор программы ===


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
Line 43: Line 41:
</syntaxhighlight>
</syntaxhighlight>


This time, the button says <strong>Quit</strong> and that's exactly what the program will do when the user clicks the button.
На этот раз кнопка называется <strong>Quit</strong> (Выход), это именно то, что она будет делать.


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
Line 49: Line 47:
</syntaxhighlight>
</syntaxhighlight>


We've chosen another size for the button since the text is a bit shorter than "Hello world!". We could also have used [http://doc.qt.nokia.com/latest/qfontmetrics.html Qt::FontMetrics] to set right size, or let [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] choose a reasonable default.
Мы выбрали другой рамер кнопки, поскольку текст будет немного короче, чем "Hello world!". Также можно было воспользоваться [http://doc.qt.nokia.com/latest/qfontmetrics.html Qt::FontMetrics], чтобы установить правильный размер, или позволить [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] самостоятельно выбрать размер кнопки.


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
Line 55: Line 53:
</syntaxhighlight>
</syntaxhighlight>


Here we choose a new font for the button, an 18-point bold font from the Times family. It is also possible to change the default font for the entire application, using [http://doc.qt.nokia.com/latest/qapplication.html#setFont Qt::Application::setFont()].
Здесь мы выбираем другой шрифт для текста на кнопке, это 18-й полужирный шрифт Times. Также можно поменять шрифт по умолчанию для всего приложения, используя [http://doc.qt.nokia.com/latest/qapplication.html#setFont Qt::Application::setFont()].


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
Line 61: Line 59:
</syntaxhighlight>
</syntaxhighlight>


[http://doc.trolltech.com/4.2/qobject.html#connect Qt::Object::connect()] is perhaps the most central feature of Qt. Note that '''<tt>connect()</tt>''' in this context is a static function in [http://doc.qt.nokia.com/latest/qobject.html Qt::Object]. Do not confuse it with the '''<tt>connect()</tt>''' function in the Berkeley socket library.
[http://doc.trolltech.com/4.2/qobject.html#connect Qt::Object::connect()] — это наверное самая важная возможность Qt. Обратите внимание на то, что здесь '''<tt>connect()</tt>''' — статический метод класса [http://doc.qt.nokia.com/latest/qobject.html Qt::Object]. Не вздумайте путать его с функцией '''<tt>connect()</tt>''' из библиотеки для работы с сокетами!


This '''<tt>connect()</tt>''' call establishes a one-way connection between two Qt objects (objects that inherit [http://doc.qt.nokia.com/latest/qobject.html Qt::Object], directly or indirectly). Every Qt object can have both '''<tt>signals</tt>''' (to send messages) and '''<tt>slots</tt>''' (to receive messages). All widgets are Qt objects, since they inherit [http://doc.qt.nokia.com/latest/qwidget.html Qt::Widget], which in turn inherits [http://doc.qt.nokia.com/latest/qobject.html Qt::Object].
Вызов '''<tt>connect()</tt>''' настраивает одностороннее соединение между двумя объектами Qt (между объектами, наследованными от [http://doc.qt.nokia.com/latest/qobject.html Qt::Object], явно или косвенно). Каждый объект Qt может иметь '''<tt>signals</tt>''' (сигналы, они служат для отправки сообщений) и '''<tt>slots</tt>''' (слоты, для получения сообщений). Все виджеты являются объектами Qt, поскольку они наследуют класс [http://doc.qt.nokia.com/latest/qwidget.html Qt::Widget], который в свою очередь наследует класс [http://doc.qt.nokia.com/latest/qobject.html Qt::Object].


Here, the '''<tt>clicked()</tt>''' signal of '''<tt>quit</tt>''' is connected to the '''<tt>quit()</tt>''' slot of '''<tt>app</tt>''', so that when the button is clicked, the application quits.
Здесь сигнал '''<tt>clicked()</tt>''' объекта '''<tt>quit</tt>''' подключается к слоту '''<tt>quit()</tt>''' объекта '''<tt>app</tt>'''. Это приводит к тому, что при нажатии кнопки приложение закрывается.


The [http://doc.qt.nokia.com/latest/signalsandslots.html Signals and Slots] documentation describes this topic in detail.
В статье [http://doc.qt.nokia.com/latest/signalsandslots.html Сигналы и слоты] из документации Qt эта тема изложена более подробно.


=== Running the Application ===
=== Запуск приложения ===


When you run this program, you will see an even smaller window than in Chapter 1, filled with an even smaller button.
После запуска приложения вы увидите небольшое окно с кнопкой, ещё меньшее, чем в первой главе.


=== Exercises ===
=== Упражнения ===


Try to resize the window. Click the button to close the application.
Попробуйте изменить размер окна. Нажмите кнопку «Quit», чтобы закрыть приложение.


Are there any other signals in [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] you can connect to quit? [Hint: The [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] inherits most of its functionality from [http://doc.qt.nokia.com/latest/qabstractbutton.html Qt::AbstractButton].]
Может быть у класса [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] есть другие сигналы, которые могут инициировать закрытие приложения? [Подсказка: класс [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] наследует большинство своих возможностей от класса [http://doc.qt.nokia.com/latest/qabstractbutton.html Qt::AbstractButton].]


[[Category:Ruby]]
[[Category:Ruby/ru]]

Latest revision as of 12:31, 13 July 2012

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

Выход по нажатию

Файлы:

Обзор

Уже создав окно в первой главе, мы заставим приложение корректно завершаться по нажатию кнопки.

Кроме того, мы научимся менять шрифт.

require 'Qt4'

app = Qt::Application.new(ARGV)

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

Qt::Object.connect(quit, SIGNAL('clicked()'), app, SLOT('quit()'))

quit.show()
app.exec()

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

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

На этот раз кнопка называется Quit (Выход), это именно то, что она будет делать.

quit.resize(75, 30)

Мы выбрали другой рамер кнопки, поскольку текст будет немного короче, чем "Hello world!". Также можно было воспользоваться Qt::FontMetrics, чтобы установить правильный размер, или позволить Qt::PushButton самостоятельно выбрать размер кнопки.

quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))

Здесь мы выбираем другой шрифт для текста на кнопке, это 18-й полужирный шрифт Times. Также можно поменять шрифт по умолчанию для всего приложения, используя Qt::Application::setFont().

Qt::Object.connect(quit, SIGNAL('clicked()'), app, SLOT('quit()'))

Qt::Object::connect() — это наверное самая важная возможность Qt. Обратите внимание на то, что здесь connect() — статический метод класса Qt::Object. Не вздумайте путать его с функцией connect() из библиотеки для работы с сокетами!

Вызов connect() настраивает одностороннее соединение между двумя объектами Qt (между объектами, наследованными от Qt::Object, явно или косвенно). Каждый объект Qt может иметь signals (сигналы, они служат для отправки сообщений) и slots (слоты, для получения сообщений). Все виджеты являются объектами Qt, поскольку они наследуют класс Qt::Widget, который в свою очередь наследует класс Qt::Object.

Здесь сигнал clicked() объекта quit подключается к слоту quit() объекта app. Это приводит к тому, что при нажатии кнопки приложение закрывается.

В статье Сигналы и слоты из документации Qt эта тема изложена более подробно.

Запуск приложения

После запуска приложения вы увидите небольшое окно с кнопкой, ещё меньшее, чем в первой главе.

Упражнения

Попробуйте изменить размер окна. Нажмите кнопку «Quit», чтобы закрыть приложение.

Может быть у класса Qt::PushButton есть другие сигналы, которые могут инициировать закрытие приложения? [Подсказка: класс Qt::PushButton наследует большинство своих возможностей от класса Qt::AbstractButton.]