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

From KDE TechBase
(Created page with "Пользователь может использовать виджет [http://doc.qt.nokia.com/latest/qslider.html Qt::Slider] (ползунок) для изменения з...")
(Created page with "Здесь мы используем механизм [http://doc.qt.nokia.com/latest/signalsandslots.html сигналов и слотов] для того, чтобы соед...")
Line 73: Line 73:
</syntaxhighlight>
</syntaxhighlight>


Here we use the [http://doc.qt.nokia.com/latest/signalsandslots.html signals and slots] mechanism to connect the slider's  [http://doc.qt.nokia.com/latest/qabstractslider.html#valueChanged QAbstractSlider::valueChanged()] signal to the LCD number's display() slot.  
Здесь мы используем механизм [http://doc.qt.nokia.com/latest/signalsandslots.html сигналов и слотов] для того, чтобы соединить сигнал ползунка [http://doc.qt.nokia.com/latest/qabstractslider.html#valueChanged QAbstractSlider::valueChanged()] со слотом «ЖК-дисплея» '''<tt>display()</tt>'''.  


Whenever the slider's value changes it broadcasts the new value by emitting the [http://doc.qt.nokia.com/latest/qabstractslider.html#valueChanged QAbstractSlider::valueChanged()] signal. Because that signal is connected to the LCD number's [http://doc.qt.nokia.com/latest/qlcdnumber.html#intValue-prop QLCDNumber::display()] slot, the slot is called when the signal is broadcast. Neither of the objects knows about the other. This is essential in component programming.  
Whenever the slider's value changes it broadcasts the new value by emitting the [http://doc.qt.nokia.com/latest/qabstractslider.html#valueChanged QAbstractSlider::valueChanged()] signal. Because that signal is connected to the LCD number's [http://doc.qt.nokia.com/latest/qlcdnumber.html#intValue-prop QLCDNumber::display()] slot, the slot is called when the signal is broadcast. Neither of the objects knows about the other. This is essential in component programming.  

Revision as of 17:30, 2 July 2011

Other languages:


Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05


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

«Кубики»

Файлы:

Обзор

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

require 'Qt4'

class MyWidget < Qt::Widget
  def initialize()
    super()
    quit = Qt::PushButton.new('Quit')
    quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))
    
    lcd = Qt::LCDNumber.new(2)

    slider = Qt::Slider.new(Qt::Horizontal)
    slider.setRange(0, 99)
    slider.setValue(0)

    connect(quit, SIGNAL('clicked()'), $qApp, SLOT('quit()'))
    connect(slider, SIGNAL('valueChanged(int)'), lcd, SLOT('display(int)'))

    layout = Qt::VBoxLayout.new()
    layout.addWidget(quit)
    layout.addWidget(lcd)
    layout.addWidget(slider)
    setLayout(layout)
  end
end

app = Qt::Application.new(ARGV)

widget = MyWidget.new()

widget.show()
app.exec()

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

    lcd = Qt::LCDNumber.new(2)

lcd — это объект класса Qt::LCDNumber, то есть виджет, показывающий числа в стиле ЖК-дисплея. В нашем случае объект настраивается на показ двух цифр.

slider = Qt::Slider.new(Qt::Horizontal)
slider.setRange(0, 99)
slider.setValue(0)

Пользователь может использовать виджет Qt::Slider (ползунок) для изменения значения числа в определённом диапазоне. Здесь мы создаём горизонтальный ползунок, устанавливаем минимальное значение в 0, максимальное значение в 99, а исходное значение равно 0.

    connect(slider, SIGNAL('valueChanged(int)'), lcd, SLOT('display(int)'))

Здесь мы используем механизм сигналов и слотов для того, чтобы соединить сигнал ползунка QAbstractSlider::valueChanged() со слотом «ЖК-дисплея» display().

Whenever the slider's value changes it broadcasts the new value by emitting the QAbstractSlider::valueChanged() signal. Because that signal is connected to the LCD number's QLCDNumber::display() slot, the slot is called when the signal is broadcast. Neither of the objects knows about the other. This is essential in component programming.

layout = Qt::VBoxLayout.new()
layout.addWidget(quit)
layout.addWidget(lcd)
layout.addWidget(slider)
setLayout(layout)

MyWidget now uses a Qt::VBoxLayout to manage the geometry of its child widgets. For that reason, we don't need to specify the screen coordinates for each widget like we did in Chapter 4. In addition, using a layout ensures that the child widgets are resized when the window is resized. Then we add the quit, lcd, and slider widgets to the layout using Qt::BoxLayout::addWidget().

The Qt::Widget::setLayout() function installs the layout on MyWidget. This makes the layout a child widget of MyWidget so we don't have to worry about deleting it; it will be deleted together with MyWidget. Also, the call to Qt::Widget::setLayout() automatically reparents the widgets in the layout so that they are children of MyWidget. Because of this, we didn't need to specify self as the parent for the quit, lcd, and slider widgets.

In Qt, widgets are either children of other widgets (e.g. self), or they have no parent. A widget can be added to a layout, in which case the layout becomes responsible for managing the geometry of that widget, but the layout can never act as a parent itself. Indeed, Qt::Widget's constructor takes a Qt::Widget pointer for the parent, and Qt::Layout doesn't inherit from Qt::Widget.

Running the Application

The LCD number reflects everything you do to the slider, and the widget handles resizing well. Notice that the LCD number widget changes in size when the window is resized (because it can), but the others stay about the same (because otherwise they would look strange).

Exercises

Try changing the LCD number to add more digits or to change mode (Qt::LCDNumber::setMode()). You can even add four push buttons to set the number base.

You can also change the slider's range.

Perhaps it would have been better to use Qt::SpinBox than a slider?

Try to make the application quit when the LCD number overflows.