Saturday, April 27, 2013

Nibbles game clone in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will create a Nibbles game clone.
Nibbles is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple, its body grows. The snake must avoid the walls and its own body.

Development

The size of each of the joints of a snake is 10px. The snake is controlled with the cursor keys. Initially, the snake has three joints. The game starts immediately. When the game is finished, we display "Game Over" message in the center of the window.
Board.rb
WIDTH = 300
HEIGHT = 300
DOT_SIZE = 10
ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE)
RAND_POS = 29
DELAY = 140

$x = [0] * ALL_DOTS
$y = [0] * ALL_DOTS

class Board < Qt::Widget

    
    def initialize(parent)
        super(parent)
        
        setFocusPolicy Qt::StrongFocus
       
        initGame
    end


    def initGame
    
        @left = false
        @right = true
        @up = false
        @down = false
        @inGame = true
        @dots = 3
        
        begin
            @ball = Qt::Image.new "dot.png"
            @apple = Qt::Image.new "apple.png"
            @head = Qt::Image.new "head.png"
        rescue
            puts "cannot load images"
        end

        for i in (0..@dots)
            $x[i] = 50 - i * 10
            $y[i] = 50
        end

        locateApple
        setStyleSheet "QWidget { background-color: #000000 }"
        
        @timer = Qt::BasicTimer.new 
        @timer.start(140, self)
        
    end


    def paintEvent event

        painter = Qt::Painter.new
        painter.begin self

        if @inGame
            drawObjects painter
        else 
            gameOver painter
        end

        painter.end
    end

    def drawObjects painter

        painter.drawImage @apple_x, @apple_y, @apple

        for z in (0..@dots)
            if z == 0
                painter.drawImage $x[z], $y[z], @head
            else 
                painter.drawImage $x[z], $y[z], @ball
            end
        end
    end

    def gameOver painter
        msg = "Game Over"
        small = Qt::Font.new "Helvetica", 12,
            Qt::Font::Bold.value
        
        metr = Qt::FontMetrics.new small
        
        textWidth = metr.width msg
        h = height
        w = width

        painter.setPen Qt::Color.new Qt::white
        painter.setFont small
        painter.translate Qt::Point.new w/2, h/2
        painter.drawText -textWidth/2, 0, msg
    end


    def checkApple

        if $x[0] == @apple_x and $y[0] == @apple_y 
            @dots = @dots + 1
            locateApple
        end
    end
    
    def move

        z = @dots

        while z > 0
            $x[z] = $x[(z - 1)]
            $y[z] = $y[(z - 1)]
            z = z - 1
        end

        if @left
            $x[0] -= DOT_SIZE
        end

        if @right 
            $x[0] += DOT_SIZE
        end

        if @up
            $y[0] -= DOT_SIZE
        end

        if @down
            $y[0] += DOT_SIZE
        end
        
     end


    def checkCollision

        z = @dots
       
        while z > 0
            if z > 4 and $x[0] == $x[z] and $y[0] == $y[z]
                @inGame = false
            end
            z = z - 1
        end

        if $y[0] > HEIGHT
            @inGame = false
        end
        
        if $y[0] < 0
            @inGame = false
        end
        
        if $x[0] > WIDTH
            @inGame = false
        end
        
        if $x[0] < 0
            @inGame = false
        end    
        
    end


    def locateApple
    
        r = rand RAND_POS
        @apple_x = r * DOT_SIZE
        r = rand RAND_POS
        @apple_y = r * DOT_SIZE
    end

    def timerEvent event

        if @inGame 
            checkApple
            checkCollision
            move
        else 
            @timer.stop
        end

        repaint
    end

    def keyPressEvent event
        
        key = event.key
        
        if key == Qt::Key_Left.value and not @right
            @left = true
            @up = false
            @down = false
        end
        
        if key == Qt::Key_Right.value and not @left
            @right = true
            @up = false
            @down = false
        end
        
        if key == Qt::Key_Up.value and not @down
            @up = true
            @right = false
            @left = false            
        end
        
        if key == Qt::Key_Down.value and not @up
            @down = true
            @right = false
            @left = false
        end
    end
end
First we will define some constants used in our game.
The WIDTH and HEIGHT constants determine the size of the Board. The DOT_SIZE is the size of the apple and the dot of the snake. The ALL_DOTS constant defines the maximum number of possible dots on the Board. The RAND_POS constant is used to calculate a random position of an apple. The DELAY constant determines the speed of the game.
$x = [0] * ALL_DOTS
$y = [0] * ALL_DOTS
These two arrays store x, y coordinates of all possible joints of a snake.
The initGame method initializes variables, loads images and starts a timeout function.
if @inGame
    drawObjects painter
else 
    gameOver painter
end
Inside the paintEvent method, we check the @inGame variable. If it is true, we draw our objects. The apple and the snake joints. Otherwise we display "Game over" text.
def drawObjects painter

    painter.drawImage @apple_x, @apple_y, @apple

    for z in (0..@dots)
        if z == 0
            painter.drawImage $x[z], $y[z], @head
        else 
            painter.drawImage $x[z], $y[z], @ball
        end
    end
end
The drawObjects method draws the apple and the joints of the snake. The first joint of a snake is its head, which is represented by a red circle.
 def checkApple

     if $x[0] == @apple_x and $y[0] == @apple_y 
         @dots = @dots + 1
         locateApple
     end
 end
The checkApple method checks, if the snake has hit the apple object. If so, we add another snake joint and call the locateApple method, which randomly places a new apple object.
In the move method we have the key algorithm of the game. To understand it, look at how the snake is moving. You control the head of the snake. You can change its direction with the cursor keys. The rest of the joints move one position up the chain. The second joint moves where the first was, the third joint where the second was etc.
while z > 0
    $x[z] = $x[(z - 1)]
    $y[z] = $y[(z - 1)]
    z = z - 1
end
This code moves the joints up the chain.
if @left
    $x[0] -= DOT_SIZE
end
Move the head to the left.
In the checkCollision method, we determine if the snake has hit itself or one of the walls.
while z > 0
    if z > 4 and $x[0] == $x[z] and $y[0] == $y[z]
        @inGame = false
    end
    z = z - 1
end
Finish the game, if the snake hits one of its joints with the head.
if $y[0] > HEIGHT
    @inGame = false
end
Finish the game, if the snake hits the bottom of the Board.
The locateApple method locates an apple randomly on the board.
r = rand RAND_POS
We get a random number from 0 to RAND_POS - 1.
@apple_x = r * DOT_SIZE
...
@apple_y = r * DOT_SIZE
These line set the x, y coordinates of the apple object.
if @inGame 
    checkApple
    checkCollision
    move
else 
    @timer.stop
end
Every 140 ms, the timerEvent method is called. If we are in the game, we call three methods, that build the logic of the game. Otherwise we stop the timer.
In the keyPressEvent method of the Board class, we determine the keys that were pressed.
if key == Qt::Key_Left.value and not @right
    @left = true
    @up = false
    @down = false
end
If we hit the left cursor key, we set @left variable to true. This variable is used in the move method to change coordinates of the snake object. Notice also, that when the snake is heading to the right, we cannot turn immediately to the left.
Nibbles.rb
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we create
# a Nibbles game clone.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'
require 'Board'

class QtApp < Qt::MainWindow
    
    def initialize
        super
        
        setWindowTitle "Nibbles"
       
        setCentralWidget Board.new(self)
       
        resize 310, 310
        move 300, 300

        show
    end
       
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the Nibbles.rb file, we set up the Nibbles game.
Nibbles
Figure: Nibbles
This was the Nibbles computer game programmed with the Qt library and the Ruby programming language.

Custom widget in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will create a custom widget.
Toolkits usually provide only the most common widgets like buttons, text widgets, sliders etc. No toolkit can provide all possible widgets. Programmers must create such widgets by themselves. They do it by using the drawing tools provided by the toolkit. There are two possibilities. A programmer can modify or enhance an existing widget. Or he can create a custom widget from scratch.

The Burning widget

In the next example, we will create a custom burning widget. This widget can be seen in applications like Nero or K3B. The widget will be created from scratch.
#!/usr/bin/ruby


# ZetCode Ruby Qt tutorial

# In this program, we create
# a custom widget
#
# @author jan bodnar
# website zetcode.com
# last modified July 2009


require 'Qt'

PANEL_HEIGHT = 30
DISTANCE = 19
LINE_WIDTH = 5
DIVISIONS = 10
FULL_CAPACITY = 700
MAX_CAPACITY = 750


class Burning < Qt::Widget 


    def initialize(parent) 
        super(parent)
        
        @num = [ "75", "150", "225", "300", 
            "375", "450", "525", "600", "675" ]
            
        @redColor = Qt::Color.new 255, 175, 175
        @yellowColor = Qt::Color.new 255, 255, 184

        @parent = parent
        setMinimumHeight PANEL_HEIGHT
    end

    
    def paintEvent event

        painter = Qt::Painter.new self
        
        drawWidget painter
        painter.end
    end

    def drawWidget painter

        w = width.to_f
        

        slid_width = @parent.getCurrentWidth
        
        step = (w / DIVISIONS).round.to_f

        till = ((w / MAX_CAPACITY) * slid_width).to_f
        full = ((w / MAX_CAPACITY) * FULL_CAPACITY).to_f

        if slid_width > FULL_CAPACITY
            painter.setPen @yellowColor
            painter.setBrush Qt::Brush.new @yellowColor
            painter.drawRect Qt::RectF.new 0, 0, full, PANEL_HEIGHT
            painter.setPen @redColor
            painter.setBrush Qt::Brush.new @redColor
            painter.drawRect Qt::RectF.new full+1, 0, till-full, PANEL_HEIGHT
        else 
            if slid_width > 0
               painter.setPen @yellowColor
               painter.setBrush Qt::Brush.new @yellowColor
               painter.drawRect Qt::RectF.new 0, 0, till, PANEL_HEIGHT
            end
        end

        painter.setPen Qt::Color.new 90, 90, 90
        painter.setBrush Qt::NoBrush
        painter.drawRect 0, 0, w-1, PANEL_HEIGHT-1

        newFont = font
        newFont.setPointSize 7
        painter.setFont newFont
        
        for i in (1..@num.length)
            painter.drawLine Qt::LineF.new i*step, 1, i*step, LINE_WIDTH

            metrics = Qt::FontMetrics.new newFont

            w = metrics.width @num[i-1]
            painter.drawText(Qt::PointF.new(i*step-w/2, DISTANCE), @num[i-1])
            
        end
    end
end

class QtApp < Qt::Widget 

    slots 'onChanged(int)'

    def initialize
        super
        setWindowTitle "The Burning Widget"

        initUI

        resize 370, 200
        move 300, 300
        show
    end

    def initUI
    
       @cur_width = 0
       
       @slider = Qt::Slider.new Qt::Horizontal , self
       @slider.setMaximum MAX_CAPACITY
       @slider.setGeometry 50, 50, 130, 30 

       connect(@slider, SIGNAL("valueChanged(int)"), self, SLOT("onChanged(int)"))
       
       vbox = Qt::VBoxLayout.new self
       hbox = Qt::HBoxLayout.new

       vbox.addStretch 1

       @widget = Burning.new self
       hbox.addWidget @widget, 0

       vbox.addLayout hbox

       setLayout vbox
    end

    def onChanged val
        @cur_width = val
        @widget.repaint
    end

    def getCurrentWidth
      return @cur_width
    end
end


app = Qt::Application.new ARGV
QtApp.new
app.exec
In this file, we create the Burning widget.
class Burning < Qt::Widget 
The custom widget is based on the Widget widget.
PANEL_HEIGHT = 30
DISTANCE = 19
LINE_WIDTH = 5
DIVISIONS = 10
FULL_CAPACITY = 700
MAX_CAPACITY = 750
These are important constants. The PANEL_HEIGHT defines the height for the custom widget. The DISTANCE is the distance of the numbers on the scale from the top of their parent border. The LINE_WIDTH is the vertical line width. The DIVISIONS is the number of parts of the scale. The FULL_CAPACITY is the maximum capacity of the media. After it is reached, overburning happens. This is visualized by a red color. The MAX_CAPACITY is the maximum capacity of a medium.
@num = [ "75", "150", "225", "300", 
    "375", "450", "525", "600", "675" ]
We use these numbers to build the scale of the Burning widget.
def paintEvent event

    painter = Qt::Painter.new self

    drawWidget painter
    painter.end
end
The drawing of the custom widget is delegated to the drawWidget method.
slid_width = @parent.getCurrentWidth
We use it to get the currently selected slider value.
w = width.to_f
We get the width of the widget. The width of the custom widget is dynamic. It can be resized by a user.
till = ((w / MAX_CAPACITY) * slid_width).to_f
full = ((w / MAX_CAPACITY) * FULL_CAPACITY).to_f
We use the w variable to do the transformations. Between the values of the scale and the custom widget's measures. Note that we use floating point values. We get greater precision in drawing.
painter.setPen @redColor
painter.setBrush Qt::Brush.new @redColor
painter.drawRect Qt::RectF.new full+1, 0, till-full, PANEL_HEIGHT
These three lines draw the red rectangle, indicating the overburning.
painter.drawRect 0, 0, w-1, PANEL_HEIGHT-1
This is the perimeter of the widget. The outside rectangle.
painter.drawLine Qt::LineF.new i*step, 1, i*step, LINE_WIDTH
Here we draw the small vertical lines.
w = metrics.width @num[i-1]
painter.drawText(Qt::PointF.new(i*step-w/2, DISTANCE), @num[i-1])
Here we draw the numbers of the scale. To precisely position the numbers, we must get the width of the string.
@widget = Burning.new self
hbox.addWidget @widget, 0
We create the instance of the Burning widget and add it to the horizontal box.
def onChanged val
    @cur_width = val
    @widget.repaint
end
When the value of the slider changes, we store it inside the @cur_width variable and repaint the custom widget.
def getCurrentWidth
return @cur_width
end
This method is called by the custom widget to get the actual slider value.
The Burning widget
Figure: The Burning widget
In this part of the Ruby Qt tutorial, we have demonstrated how to create a custom widget.

Painting in Ruby Qt

In this part of the Ruby Qt programming tutorial we will do some painting.
When do we need to paint? There are situations, when we need to create a widget from scratch. In such a case, we need to do painting. Or we want to create charts, special ornaments, effects or widget enhancements.
The Painter class is instrumental when we do some painting in the Qt library. Paint events are received in the paintEvent method. To do custom painting, we must reimplement this method.

Patterns

In Qt, there are various patterns, that we can use to fill the interiors of shapes.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program draws nine rectangles.
# The interiors are filled with
# different built-in patterns.
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: June 2009

require 'Qt'

class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Patterns"
        
        resize 350, 280
        move 300, 300

        show
    end
    
    
    def paintEvent event

        painter = Qt::Painter.new self
        
        drawPatterns painter
        painter.end
    end

    
    def drawPatterns painter

        painter.setPen Qt::NoPen

        painter.setBrush Qt::HorPattern
        painter.drawRect 10, 15, 90, 60

        painter.setBrush Qt::VerPattern
        painter.drawRect 130, 15, 90, 60

        painter.setBrush Qt::CrossPattern
        painter.drawRect 250, 15, 90, 60

        painter.setBrush Qt::Dense7Pattern
        painter.drawRect 10, 105, 90, 60

        painter.setBrush Qt::Dense6Pattern
        painter.drawRect 130, 105, 90, 60

        painter.setBrush Qt::Dense5Pattern
        painter.drawRect 250, 105, 90, 60

        painter.setBrush Qt::BDiagPattern
        painter.drawRect 10, 195, 90, 60

        painter.setBrush Qt::FDiagPattern
        painter.drawRect 130, 195, 90, 60

        painter.setBrush Qt::DiagCrossPattern
        painter.drawRect 250, 195, 90, 60
    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the code example, we will draw nine rectangles and fill them with different brush patterns.
def paintEvent event

    painter = Qt::Painter.new self

    drawPatterns painter
    painter.end
end
When the window area needs to be redrawn, the paintEvent method is called. This happens, when we resize the window, maximize it or minimize it etc. Inside this method, we create the Painter object. This object is used to do all painting in Qt. The painting itself is delegated to the drawPatterns method.
painter.setPen Qt::NoPen
The pen object is used to draw outlines of the shapes. In our example we will not use a pen.
painter.setBrush Qt::HorPattern
We set a horizontal pattern as a brush.
painter.drawRect 10, 15, 90, 60
We draw a rectangle, with the current pen and brush. The first two parameters of the method are the x, y coordinates. The last two parameters are the width and height of the rectangle.
painter.end
Ends painting. Any resources used while painting are released.
Patterns
Figure: Patterns

Shapes

The Qt painting API can draw various shapes. The following programming code example will show some of them.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program draws basic shapes
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: June 2009

require 'Qt'

class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Basic shapes"
        
        resize 350, 280
        move 300, 300

        show
    end
    
    
    def paintEvent event

          painter = Qt::Painter.new self
        
          drawShapes painter
          painter.end
    end

    
    def drawShapes painter

        painter.setRenderHint Qt::Painter::Antialiasing
        painter.setPen Qt::Color.new 150, 150, 150
        painter.setBrush Qt::Brush.new Qt::Color.new 150, 150, 150

        path1 = Qt::PainterPath.new

        path1.moveTo 5, 5
        path1.cubicTo 40, 5,  50, 50,  99, 99
        path1.cubicTo 5, 99,  50, 50,  5, 5
        painter.drawPath path1

        painter.drawPie 130, 20, 90, 60, 30*16, 120*16
        painter.drawChord 240, 30, 90, 60, 0, 16*180
        painter.drawRoundRect 20, 120, 80, 50

        points = []
        points.push  Qt::Point.new 130, 140
        points.push  Qt::Point.new 180, 170
        points.push  Qt::Point.new 180, 140
        points.push  Qt::Point.new 220, 110
        points.push  Qt::Point.new 140, 100

        polygon = Qt::Polygon.new points

        painter.drawPolygon polygon
        painter.drawRect 250, 110, 60, 60

        baseline = Qt::PointF.new 20, 250
        font = Qt::Font.new "Georgia", 55
        path2 = Qt::PainterPath.new
        path2.addText baseline, font, "Q"
        painter.drawPath path2

        painter.drawEllipse 140, 200, 60, 60
        painter.drawEllipse 240, 200, 90, 60

    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In this code example, we draw nine different shapes on the window. A complex path, a pie, a chord, a rounded rectangle, a polygon, a rectangle, a character based shape, a circle and an ellipse.
painter.setRenderHint Qt::Painter::Antialiasing
We use antialiasing in the example. Antialiased shapes look better, but it takes more time to draw them.
painter.setPen Qt::Color.new 150, 150, 150
painter.setBrush Qt::Brush.new Qt::Color.new 150, 150, 150
We use a dark gray pen and brush to draw the shapes.
path1 = Qt::PainterPath.new

path1.moveTo 5, 5
path1.cubicTo 40, 5,  50, 50,  99, 99
path1.cubicTo 5, 99,  50, 50,  5, 5
painter.drawPath path1
The first complex shape is created with the PainterPath object. The PainterPath class provides a container for painting operations. A painter path is an object composed of a number of graphical building blocks, such as rectangles, ellipses, lines, and curves.
painter.drawPie 130, 20, 90, 60, 30*16, 120*16
painter.drawChord 240, 30, 90, 60, 0, 16*180
painter.drawRoundRect 20, 120, 80, 50
These three lines draw a pie, a chord and a rounded rectangle.
points = []
points.push  Qt::Point.new 130, 140
points.push  Qt::Point.new 180, 170
points.push  Qt::Point.new 180, 140
points.push  Qt::Point.new 220, 110
points.push  Qt::Point.new 140, 100

polygon = Qt::Polygon.new points

painter.drawPolygon polygon
We use an array of five points to create a polygon.
baseline = Qt::PointF.new 20, 250
font = Qt::Font.new "Georgia", 55
path2 = Qt::PainterPath.new
path2.addText baseline, font, "Q"
painter.drawPath path2
These lines create a character based shape.
 painter.drawEllipse 140, 200, 60, 60
 painter.drawEllipse 240, 200, 90, 60
These two lines create a circle and an ellipse respectively.
Shapes
Figure: Shapes

Transparent rectangles

Transparency is the quality of being able to see through a material. The easiest way to understand transparency is to imagine a piece of glass or water. Technically, the rays of light can go through the glass and this way we can see objects behind the glass.
In computer graphics, we can achieve transparency effects using alpha compositing. Alpha compositing is the process of combining an image with a background to create the appearance of partial transparency. The composition process uses an alpha channel. (wikipedia.org, answers.com)
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program draws ten
# rectangles with different
# levels of transparency.
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: June 2009

require 'Qt'

class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Transparent rectangles"
        
        resize 590, 90
        move 300, 300

        show
    end
    
    
    def paintEvent event

          painter = Qt::Painter.new self
        
          drawRectangles painter
          painter.end
    end

    
    def drawRectangles painter

        painter.setPen Qt::NoPen

        for i in 1..10
            painter.setBrush Qt::Brush.new Qt::Color.new 0, 0, 255, i*25
            painter.drawRect 50*i, 20, 40, 40
        end

    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the example we will draw ten rectangles with different levels of transparency.
 painter.setPen Qt::NoPen
We use no pen.
for i in 1..10
    painter.setBrush Qt::Brush.new Qt::Color.new 0, 0, 255, i*25
    painter.drawRect 50*i, 20, 40, 40
end
The last parameter of the Color object is the alpha transparency value.
Transparent rectangles
Figure: Transparent rectangles

Donut Shape

In the following example we create a complex shape by rotating a bunch of ellipses.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program draws a donut
# shape
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: June 2009

require 'Qt'

class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Donut"
        
        resize 350, 280
        move 300, 300

        show
    end
    
    
    def paintEvent event

          painter = Qt::Painter.new self
        
          drawDonut painter
          painter.end
    end

    
    def drawDonut painter

        painter.setRenderHint Qt::Painter::Antialiasing

        color = Qt::Color.new
        color.setNamedColor "#333333"

        pen = Qt::Pen.new color
        pen.setWidth 1
        painter.setPen pen

        w = width
        h = height

        painter.translate Qt::Point.new w/2, h/2

        72.times do
            painter.drawEllipse -125, -40, 250, 80
            painter.rotate 5.0
        end
    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In this example, we create a donut. The shape resembles a cookie, hence the name donut.
color = Qt::Color.new
color.setNamedColor "#333333"
We can use a hexadecimal notation to create a color object.
w = width
h = height
Here we determine the width and height of the window.
painter.translate Qt::Point.new w/2, h/2
We move the coordinate system to the middle of the window. This way we make the drawing mathematically easier.
72.times do
    painter.drawEllipse -125, -40, 250, 80
    painter.rotate 5.0
end
We draw an ellipse object 72 times. Each time, we rotate the ellipse by 5 degrees. This will create our donut shape.
Donut
Figure: Donut

Drawing text

In the last example, we are going to draw text on the window.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program draws text
# on the window
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: June 2009

require 'Qt'

class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Soulmate"
        
        resize 370, 240
        move 300, 300

        show
    end
    
    
    def paintEvent event

          painter = Qt::Painter.new self
        
          drawText painter
          painter.end
    end

    
    def drawText painter

        painter.setBrush Qt::Brush.new Qt::Color.new 25, 25, 25
        painter.setFont Qt::Font.new "Purisa", 10

        painter.drawText Qt::Point.new(20, 30),
                "Most relationships seem so transitory"
        painter.drawText Qt::Point.new(20, 60),
                "They're good but not the permanent one"
        painter.drawText Qt::Point.new(20, 120),
                "Who doesn't long for someone to hold"
        painter.drawText Qt::Point.new(20, 150),
                "Who knows how to love without being told"
        painter.drawText Qt::Point.new(20, 180),
                "Somebody tell me why I'm on my own"
        painter.drawText Qt::Point.new(20, 210),
                "If there's a soulmate for everyone"

    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
We draw a song lyrics on the window.
painter.setFont Qt::Font.new "Purisa", 10
We set a Purisa font for our text.
painter.drawText Qt::Point.new(20, 30),
        "Most relationships seem so transitory"
The drawText method is used to draw the text.
Drawing text
Figure: Drawing text
In this part of the Ruby Qt programming tutorial, we did some painting.

Dialogs in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will work with dialogs.
Dialog windows or dialogs are an indispensable part of most modern GUI applications. A dialog is defined as a conversation between two or more persons. In a computer application a dialog is a window which is used to "talk" to the application. A dialog is used to input data, modify data, change the application settings etc. Dialogs are important means of communication between a user and a computer program.

Message boxes

Message boxes are convenient dialogs that provide messages to the user of the application. The message consists of text and image data.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program demonstrates
# MessageBox dialogs
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: July 2009

require 'Qt'


class QtApp < Qt::Widget

    slots 'showDialog()'

    def initialize
        super
        
        setWindowTitle "Message dialogs"
       
        init_ui
       
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
    
        grid = Qt::GridLayout.new self
        grid.setSpacing 2

        error = Qt::PushButton.new "Error", self
        warning = Qt::PushButton.new "Warning", self
        question = Qt::PushButton.new "Question", self
        information = Qt::PushButton.new "Information", self
        about = Qt::PushButton.new "About", self

        grid.addWidget error, 0, 0
        grid.addWidget warning, 0, 1
        grid.addWidget question, 1, 0
        grid.addWidget information, 1, 1
        grid.addWidget about, 2, 0

        connect(error, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))
        
        connect(warning, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))
            
        connect(question, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))
            
        connect(information, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))
            
        connect(about, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))

    end   
    
    def showDialog
        
        button = sender

        if "Error" == button.text
            Qt::MessageBox.critical self, "Error", "Error loading file!"
        elsif "Warning" == button.text
            Qt::MessageBox.warning self, "Warning", "Operation not permitted!"
        elsif "Question" == button.text
            Qt::MessageBox.question self, "Question", "Are you sure to quit?"
        elsif "Information" == button.text
            Qt::MessageBox.information self, "Information", "Download completed."
        elsif "About" == button.text
            Qt::MessageBox.about self, "About", "ZetCode Ruby Qt tutorial."
        end
    end

end

app = Qt::Application.new ARGV
QtApp.new
app.exec
We use the GridLayout manager to set up a grid of five buttons. Each of the buttons shows a different message box.
if "Error" == button.text
    Qt::MessageBox.critical self, "Error", "Error loading file!"
In case we pressed the error button, we show the error dialog. We use static methods of the MessageBox class to show the message boxes.
Information message dialog
Figure: Info dialog

InputDialog

The InputDialog class provides a simple convenience dialog to get a single value from the user. The input value can be a string, a number or an item from a list. A label must be set to tell the user what they should enter.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program shows an input
# dialog
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: July 2009

require 'Qt'


class QtApp < Qt::Widget

    slots 'showDialog()'

    def initialize
        super
        
        setWindowTitle "Input dialog"
       
        init_ui
       
        resize 400, 80
        move 300, 300

        show
    end
    
    def init_ui
    
        show = Qt::PushButton.new "Dialog", self

        connect(show, SIGNAL("clicked()"),
            self, SLOT("showDialog()"))

        show.move 20, 20

        @edit = Qt::LineEdit.new self
        @edit.move 130, 22


    end   
    
    def showDialog
        
        text = Qt::InputDialog.getText self, "Input Dialog",
            "Enter your name"
         
        if text != nil 
            name = text.strip
            if not name.empty?
                @edit.setText name
            end
        end
    end

end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the code example, we have a button and a line edit. The button shows an input dialog. We get some text and the text is shown in the line edit widget.
text = Qt::InputDialog.getText self, "Input Dialog",
    "Enter your name"
The getText static method creates the input dialog. The text from the dialog is stored in the text variable.
if text != nil 
    name = text.strip
    if not name.empty?
        @edit.setText name
    end
end
Before we update the line edit, we ensure, that the text variable is not null and that it is not empty and does not consists only from spaces.
Input dialog
Figure: Input dialog

ColorDialog

The ColorDialog class provides a dialog widget for specifying colors. The color dialog's function is to allow users to choose colors.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we use the
# ColorDialog to change the color
# of a label text
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: July 2009

require 'Qt'


class QtApp < Qt::Widget

    slots 'showDialog()'

    def initialize
        super
        
        setWindowTitle "Color dialog"
       
        init_ui
       
        resize 400, 300
        move 300, 300

        show
    end
    
    def init_ui
    
        @label = Qt::Label.new "ZetCode Ruby Qt tutorial", self

        vbox = Qt::VBoxLayout.new self
        @label.setAlignment Qt::AlignCenter
        vbox.addWidget @label

    end   
    
    def mousePressEvent event

        color = Qt::ColorDialog.getColor

        if not color.isValid
            return
        end

        @label.setStyleSheet "QWidget { color: %s }" % color.name
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec

We show a some text in the center of the window. By clicking on the area of the window, we show a color dialog. We change the text foreground color to the selected color from the dialog.
def mousePressEvent event
    ...
end
In order to receive mouse press events for our window, we must reimplement the mousePressEvent method.
color = Qt::ColorDialog.getColor
The ColorDialog is being created. The selected color is stored in the color variable.
@label.setStyleSheet "QWidget { color: %s }" % color.name
Here we update the foreground color of the label's text.
ColorDialog
Figure: ColorDialog

FontDialog

The FontDialog class provides a dialog widget for selecting a font.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we use the
# FontDialog to change the font
# of a label text
#
# author: jan bodnar
# website: www.zetcode.com
# last modified: July 2009

require 'Qt'


class QtApp < Qt::Widget

    slots 'showDialog()'

    def initialize
        super
        
        setWindowTitle "Font dialog"
       
        init_ui
       
        resize 400, 300
        move 300, 300

        show
    end
    
    def init_ui
    
        @label = Qt::Label.new "ZetCode Ruby Qt tutorial", self

        vbox = Qt::VBoxLayout.new self
        @label.setAlignment Qt::AlignCenter
        vbox.addWidget @label

    end   
    
    def mousePressEvent event

        ok = Qt::Boolean.new
        font = Qt::FontDialog.getFont ok
        
        if not ok 
            return
        end

        @label.setFont font
    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
This example is similar to the previous one. This time, we change the font of the text.
font = Qt::FontDialog.getFont ok
The FontDialog is being created.
if not ok 
    return
end
The boolean ok variable is true, if we clicked on the OK button of the dialog. We return from the method, if the cancel button was pressed.
@label.setFont font
We update the label to the newly selected font.
FontDialog
Figure: FontDialog
In this part of the Ruby Qt tutorial, we worked with dialog windows.

Menus And toolbars in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will work with menus and toolbar.

A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus. While in console applications you had to remember all those arcane commands, here we have most of the commands grouped into logical parts. There are accepted standards that further reduce the amount of time spending to learn a new application. Menus group commands that we can use in an application. Toolbars provide a quick access to the most frequently used commands.

Simple menu

The first example will show a simple menu.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program shows a simple
# menu. It has one action, which
# will terminate the program, when
# selected. 
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: November 2012

require 'Qt'


class QtApp < Qt::MainWindow

    def initialize
        super
        
        setWindowTitle "Simple menu"
        
        init_ui
        
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
        quit = Qt::Action.new "&Quit", self

        file = menuBar().addMenu "&File"
        file.addAction quit

        connect(quit, SIGNAL("triggered()"), 
            Qt::Application.instance, SLOT("quit()"))
    end
        
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
We have a menubar, a menu and an action. In order to work with menus, we must inherit from MainWindow widget.
quit = Qt::Action.new "&Quit", self
This code line creates a Action. Each Menu has one or more action objects. Note the ampersand (&) character. It creates a shortcut for the item. Alt + Q. It also underlines the Q character. The shortcut is active, when the file menu is dropped down.
file = menuBar().addMenu "&File"
file.addAction quit
We create a Menu object. The ampersand character creates a shortcut. Alt + F. The consecutive shortcuts Alt + F, Alt + Q quit the application.
connect(quit, SIGNAL("triggered()"), 
    Qt::Application.instance, SLOT("quit()"))
When we select this option from the menu, the application quits.
Simple menu
Figure: Simple menu

Submenu

A submenu is a menu plugged into another menu object. The next example demonstrates this.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program creates a
# submenu
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: November 2012

require 'Qt'


class QtApp < Qt::MainWindow

    def initialize
        super
        
        setWindowTitle "Submenu"
        
        init_ui
        
        resize 280, 200
        move 300, 300

        show
    end
    
    def init_ui
        quit = Qt::Action.new "&Quit", self

        file = menuBar().addMenu "&File"
        impm = Qt::Menu.new "Import"

        seeds = Qt::Action.new "Import news feed...", self
        marks = Qt::Action.new "Import bookmarks...", self
        mail = Qt::Action.new "Import mail...", self
        
        impm.addAction seeds
        impm.addAction marks
        impm.addAction mail

        file.addMenu impm
        file.addAction quit

        connect(quit, SIGNAL("triggered()"), 
            Qt::Application.instance, SLOT("quit()"))
    end    
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the example, we have three options in a submenu of a file menu.
file = menuBar().addMenu "&File"
impm = Qt::Menu.new "Import"
We have two Menu objects. The file menu and the import menu.
seeds = Qt::Action.new "Import news feed...", self
marks = Qt::Action.new "Import bookmarks...", self
mail = Qt::Action.new "Import mail...", self
We create three action objects.
impm.addAction seeds
impm.addAction marks
impm.addAction mail
We add the action objects into the import menu.
file.addMenu impm
Finally, we add the import menu into the file menu.
Submenu
Figure: Submenu

Images, menus, separators

In the following example, we will further enhance our previous application. We will add icons to the menus, use shortcuts and a separator. Note that the Gnome desktop might be configured not to display menu icons by default. In such a case we need to enable the menu_have_icons option in the Gnome interface configuration.
gconftool-2 --type Boolean --set /desktop/gnome/interface/menus_have_icons True
We can use the above command or the gconf-editor tool.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program shows image
# menus, shortcuts and a separator
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: November 2012

require 'Qt'


class QtApp < Qt::MainWindow

    def initialize
        super
        
        setWindowTitle "Image menu"
        
        init_ui
        
        resize 280, 200
        move 300, 300

        show
    end
    
    def init_ui
        newpix = Qt::Icon.new "new.png"
        openpix = Qt::Icon.new "open.png"
        quitpix = Qt::Icon.new "exit.png"

        newa = Qt::Action.new newpix, "&New", self
        open = Qt::Action.new openpix, "&Open", self
        quit = Qt::Action.new quitpix, "&Quit", self
        quit.setShortcut "Ctrl+Q"
        
        file = menuBar().addMenu "&File"
        file.addAction newa
        file.addAction open
        file.addSeparator
        file.addAction quit

        connect(quit, SIGNAL("triggered()"), 
            Qt::Application.instance, SLOT("quit()"))
    end    
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In our example, we have one menu with three actions. Only the quit action will actually do something, if we select it. We also create a separator and a Ctrl + Q shortcut, which will terminate the application.
newpix = Qt::Icon.new "new.png"
openpix = Qt::Icon.new "open.png"
quitpix = Qt::Icon.new "exit.png"
These are png images, that we will use in the application.
newa = Qt::Action.new newpix, "&New", self
open = Qt::Action.new openpix, "&Open", self
quit = Qt::Action.new quitpix, "&Quit", self
Here we create three action objects. The first parameter is the Icon.
quit.setShortcut "Ctrl+Q"
This line creates a shortcut. By pressing this shortcut, we will run the quit action, which will quit the application.
file.addSeparator
We create a separator. The separator is a horizontal line, which enables us to group menu actions into some logical parts.
Images, shortcut and a separator
Figure: Images, shortcut and a separator

A toolbar

The ToolBar class provides a movable panel that contains a set of controls, which provide a quick access to the application actions.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program creates a 
# toolbar
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: November 2012

require 'Qt'


class QtApp < Qt::MainWindow

    def initialize
        super
        
        setWindowTitle "Toolbar"
        
        init_ui
        
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
        newpi = Qt::Icon.new "new2.png"
        openpi = Qt::Icon.new "open2.png"
        quitpi = Qt::Icon.new "exit2.png"

        toolbar = addToolBar "main toolbar"
        toolbar.addAction newpi, "New File" 
        toolbar.addAction openpi, "Open File"
        toolbar.addSeparator
        quit = toolbar.addAction quitpi, "Quit Application"

        connect(quit, SIGNAL("triggered()"), 
            Qt::Application.instance, SLOT("quit()"))
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
We create a toolbar with three action objects and one separator.
newpi = Qt::Icon.new "new2.png"
openpi = Qt::Icon.new "open2.png"
quitpi = Qt::Icon.new "exit2.png"
Toolbar action objects will display these icons.
toolbar = addToolBar "main toolbar"
The addToolBar method of the MainWindow creates a toolbar for the application. The text string gives a toolbar a name. This name is used to reference this toolbar, because there can be multiple toolbars in one application. If we right click on the window area, we can see a checkable option, which shows/hides the toolbar.
toolbar.addSeparator
We create a vertical separator.
connect(quit, SIGNAL("triggered()"), 
    Qt::Application.instance, SLOT("quit()"))
When we click on the quit action object, the application terminates.
Toolbar
Figure: Toolbar

Undo redo

The following example demonstrates, how we can deactivate toolbar buttons on the toolbar. It is a common practice in GUI programming. For example the save button. If we save all changes of our document to the disk, the save button is deactivated in most text editors. This way the application indicates to the user, that all changes are already saved.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program disables/enables
#  actions on a toolbar
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: November 2012

require 'Qt'


class QtApp < Qt::MainWindow

    slots 'count()'

    def initialize
        super
        
        setWindowTitle "Toolbar"
        
        init_ui
        
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
        
        @count = 2
    
        undoi = Qt::Icon.new "undo.png"
        redoi = Qt::Icon.new "redo.png"
        quitpi = Qt::Icon.new "quit.png"

        toolbar = addToolBar "first toolbar"

        @und = toolbar.addAction undoi, "Undo"
        @red = toolbar.addAction redoi, "Redo"

        connect @und, SIGNAL("triggered()"), self, SLOT("count()")
        connect @red, SIGNAL("triggered()"), self, SLOT("count()")

        toolbar.addSeparator

        quit = toolbar.addAction quitpi, "Quit Application"

        connect quit, SIGNAL("triggered()"), 
            Qt::Application.instance, SLOT("quit()")
    end
    
    def count
        
        action = sender
        
        if "Undo" == action.text
            @count = @count - 1
        else 
            @count = @count + 1
        end

        if @count <= 0
            @und.setDisabled true
            @red.setDisabled false
        end

        if @count >= 5
            @und.setDisabled false
            @red.setDisabled true
        end
        
    end   
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In our example, we have three Action objects and a separator. After several clicks on the undo or redo buttons, they become deactivated. Visually, the buttons are grayed out.
@count = 2
The @count variable determines, which button is activated and deactivated.
connect @und, SIGNAL("triggered()"), self, SLOT("count()")
connect @red, SIGNAL("triggered()"), self, SLOT("count()")
Clicking on the toolbar button, the triggered signal is emitted. We connect this signal to the count method.
action = sender
Both toolbar buttons call the count method. We need to tell between them. This line determines, which action object actually emitted the signal.
if "Undo" == action.text
    @count = @count - 1
else 
    @count = @count + 1
end
The undo toolbar button subtracts 1 from the count variable. The redo adds 1. Depending on the value of the count variable, we enable/disable the toolbar buttons.
if @count <= 0
    @und.setDisabled true
    @red.setDisabled false
end
The setDisabled method activates or deactivates the toolbar buttons.
Undo redo
Figure: Undo redo
In this part of the Ruby Qt tutorial, we mentioned the menus and toolbars.

Widgets in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will cover basic widgets.
Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar. Qt has a rich set of widgets which covers most of the programming needs. More specialized widgets can be created as custom widgets.

Qt::CheckBox

The Qt::CheckBox is a widget, that has two states. On and Off. The On state is visualized by a check mark. It is used to denote some boolean property. The Qt::CheckBox widget provides a checkbox with a text label.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program uses Qt::CheckBox
# widget to show/hide the title
# of the window.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    slots 'on_toggled(bool)'

    def initialize
        super
        
        setWindowTitle "Qt::CheckBox"
       
        init_ui
       
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
        cb = Qt::CheckBox.new "Show Title", self
        cb.setChecked true
        connect cb, SIGNAL("toggled(bool)"), 
            self, SLOT("on_toggled(bool)")

        cb.move 50, 50

    end
    
    def on_toggled state
        if state
            setWindowTitle "Qt::CheckBox"
        else
            setWindowTitle ""
        end
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In our example, we place a check box on the window. The check box shows/hides the title of the window.
setWindowTitle "Qt::CheckBox"
During the construction of the window, we set a title for the window.
cb = Qt::CheckBox.new "Show Title", self
The Qt::CheckBox widget is created. The first parameter of the constructor is its text label. The second parameter is the parent widget.
cb.setChecked true
The title is visible at the start of the application. So the check box must be checked too.
connect cb, SIGNAL("toggled(bool)"), 
    self, SLOT("on_toggled(bool)")
The toggled signal is emitted when the state of a check box changes. When the signal is emitted, we trigger the on_toggled method.
if state
    setWindowTitle "Qt::CheckBox"
else
    setWindowTitle ""
end
Depending on the state of the check box, we show or hide the title of the window.
Qt::CheckBox
Figure: Qt::CheckBox

Qt::Label

The Qt::Label widget is used to display text or image. No user interaction is available.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program uses Qt::Label widget to 
# show lyrics of a song.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "You know I'm no Good"
       
        init_ui
       
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
       text = "Meet you downstairs in the bar and heard
your rolled up sleeves and your skull t-shirt
You say why did you do it with him today?
and sniff me out like I was Tanqueray\n
cause you're my fella, my guy
hand me your stella and fly
by the time I'm out the door
you tear men down like Roger Moore\n
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good"

        label = Qt::Label.new text, self
        label.setFont Qt::Font.new "Purisa", 9

        vbox = Qt::VBoxLayout.new
        vbox.addWidget label
        setLayout vbox
    end   
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
Our example shows lyrics of a song in the window.
       text = "Meet you downstairs in the bar and heard
your rolled up sleeves and your skull t-shirt
...
We define a multi line text.
label = Qt::Label.new text, self
label.setFont Qt::Font.new "Purisa", 9
We create the label widget and change its font.
vbox = Qt::VBoxLayout.new
vbox.addWidget label
setLayout vbox
Instead of manually coding the position and size of the label, we put the label into a box layout.
Qt::Label
Figure: Qt::Label

Qt::LineEdit

The Qt::LineEdit is a widget that allows to enter and edit a single line of plain text. There are undo/redo, cut/paste and drag & drop functions available for a Qt::LineEdit widget.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program shows text
# which is entered in a Qt::LineEdit
# widget in a Qt::Label widget.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    slots 'on_changed(QString)'

    def initialize
        super
        
        setWindowTitle "LineEdit"
       
        init_ui
       
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
    
        @label = Qt::Label.new self

        edit = Qt::LineEdit.new self
        connect edit, SIGNAL("textChanged(QString)"),
            self, SLOT("on_changed(QString)")

        edit.move 60, 100
        @label.move 60, 40

    end
    
    def on_changed text
        @label.setText text
        @label.adjustSize
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In our example we show two widgets. A line edit and a label widget. The text entered into the line edit is shown in the label widget.
edit = Qt::LineEdit.new self
The Qt::LineEdit widget is created.
connect edit, SIGNAL("textChanged(QString)"),
    self, SLOT("on_changed(QString)")
When we type or delete some text from the line edit, the on_changed method is triggered.
def on_changed text
    @label.setText text
    @label.adjustSize
end
In the on_changed method, we set the contents of the line edit to the label widget. The adjustSize method ensures that all text is visible.
Qt::LineEdit widget
Figure: Qt::LineEdit widget

Toggle buttons

Toggle buttons are push buttons with a checkable flag set. Toggle button is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program uses toggle buttons to
# change the background colour of
# a widget.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    slots 'on_clicked()'

    def initialize
        super
        
        setWindowTitle "Toggle button"
       
        init_ui
       
        resize 300, 180
        move 300, 300

        show
    end
    
    def init_ui

        @color = Qt::Color.new 0, 0, 0

        setGeometry 300, 300, 280, 170
        setWindowTitle "ToggleButton"

        @redb = Qt::PushButton.new 'Red', self
        @redb.setCheckable true
        @redb.move 10, 10

        connect @redb, SIGNAL("clicked()"), SLOT("on_clicked()")
        
        @greenb = Qt::PushButton.new 'Green', self
        @greenb.setCheckable true
        @greenb.move 10, 60

        connect @greenb, SIGNAL('clicked()'), SLOT("on_clicked()")

        @blueb = Qt::PushButton.new "Blue", self
        @blueb.setCheckable true
        @blueb.move 10, 110

        connect @blueb, SIGNAL("clicked()"), SLOT("on_clicked()")
        @square = Qt::Widget.new self
        @square.setGeometry 150, 20, 100, 100
        @square.setStyleSheet "QWidget { background-color: %s }" % @color.name
    end
    
    def on_clicked
        red = @color.red
        green = @color.green
        blue = @color.blue
        
        if @redb.isChecked
            red = 255
        else 
            red = 0
        end
  
        if @greenb.isChecked
            green = 255
        else 
            green = 0
        end

        if @blueb.isChecked
            blue = 255
        else 
            blue = 0
        end
        
        @color = Qt::Color.new red, green, blue

        @square.setStyleSheet("QWidget { background-color: %s }" % @color.name) 
    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In the code example, we use three toggle buttons to change the colour of a rectangular widget.
@redb = Qt::PushButton.new 'Red', self
@redb.setCheckable true
We create a Qt::PushButton widget. The setCheckable method changes the push button into a toggle button.
connect @redb, SIGNAL("clicked()"), SLOT("on_clicked()")
We plug the button into the on_clicked method call.
@square = Qt::Widget.new self
@square.setGeometry 150, 20, 100, 100
@square.setStyleSheet "QWidget { background-color: %s }" % @color.name
We create a square widget. We set its size. At the beginning, it is black. In Qt, we use style sheets to customize the appearance of a widget.
Inside the on_clicked method, we determine the colour value and update the square widget to a new colour.
red = @color.red
green = @color.green
blue = @color.blue
Here we determine the current colour of the square widget.
if @redb.isChecked
    red = 255
else 
    red = 0
end
The red part of the colour is changed, depending on the state of the red toggle button.
@color = Qt::Color.new red, green, blue
We create a new colour value.
@square.setStyleSheet("QWidget { background-color: %s }" % @color.name) 
The colour of the square is updated.
Toggle buttons
Figure: Toggle buttons

Qt::ComboBox

The Qt::ComboBox is a widget that allows the user to choose from a list of options. It is a selection widget that displays the current item, and can pop up a list of selectable items. A combo box may be editable. It presents a list of options to the user in a way that takes up the minimum amount of screen space.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# This program uses the Qt::ComboBox widget.
# The option selected from the combo box is
# displayed in the label widget.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: Sepetmber 2012

require 'Qt'


class QtApp < Qt::Widget

    slots 'on_activated(QString)'

    def initialize
        super
        
        setWindowTitle "Qt::ComboBox"
       
        init_ui
       
        resize 250, 150
        move 300, 300

        show
    end
    
    def init_ui
    
        @label = Qt::Label.new "Ubuntu", self

        combo = Qt::ComboBox.new self

        combo.addItem "Ubuntu"
        combo.addItem "Fedora"
        combo.addItem "Mandriva"
        combo.addItem "Red Hat"
        combo.addItem "Mint"

        connect combo, SIGNAL("activated(QString)"),
            self, SLOT("on_activated(QString)")
        
        combo.move 50, 30
        @label.move 50, 100

    end
    
    def on_activated text
        @label.setText text
        @label.adjustSize
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In our code example, we have two widgets. A combo box and a label widget. The option selected from a combo box is shown in the label.
@label = Qt::Label.new "Ubuntu", self
This is the label, that will show the currently selected option from the combo box.
combo = Qt::ComboBox.new self
We create the instance of the Qt::ComboBox widget.
combo.addItem "Ubuntu"
combo.addItem "Fedora"
combo.addItem "Mandriva"
combo.addItem "Red Hat"
combo.addItem "Mint"
Combo box is filled with values.
connect combo, SIGNAL("activated(QString)"),
    self, SLOT("on_activated(QString)")
When we select an option from the combo box, the on_activated method is triggered.
def on_activated text
    @label.setText text
    @label.adjustSize
end
In the on_activated method, we update the label widget to the currently selected string from the combo box.
Qt::ComboBox widget
Figure: Qt::ComboBox widget
In this part of the Ruby Qt tutorial, we have presented several Qt widgets.

Layout management in Ruby Qt

In this part of the Ruby Qt programming tutorial, we will introduce layout managers.
When we design the GUI of our application, we decide what components we will use and how we will organize those components in the application. To organize our components, we use specialized non visible objects called layout managers. There are several options in Qt. We can use absolute positioning, built-in layout managers or create a custom layout manager. We can also visually build the layouts using the Qt Designer.
Qt has some important built-in layout managers. The Qt::VBoxLayout class lines up widgets vertically. Qt::HBoxLayout lines up widgets horizontally. The Qt::GridLayout class lays out widgets in a grid. The grid layout is the most flexible layout manager. The box layouts can be nested into one another to create complex layouts.

Absolute positioning

In most cases, programmers should use layout managers. There are a few situations, where we can use absolute positioning. In absolute positioning, the programmer specifies the position and the size of each widget in pixels. The size and the position of a widget do not change, if you resize a window. Applications look different on various platforms, and what looks OK on Linux, might not look OK on Mac. Changing fonts in your application might spoil the layout. If you translate your application into another language, you must redo your layout. For all these issues, use the absolute positioning only when you have a reason to do so.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we lay out widgets
# using absolute positioning.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012


require 'Qt'


class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Absolute"
        
        init_ui
        
        resize 300, 280
        move 300, 300

        show
    end
    
    def init_ui
    
        setStyleSheet "QWidget { background-color: #414141 }"

        bardejov = Qt::Pixmap.new "bardejov.jpg"
        rotunda = Qt::Pixmap.new "rotunda.jpg"
        mincol = Qt::Pixmap.new "mincol.jpg"

        barLabel = Qt::Label.new self
        barLabel.setPixmap bardejov
        barLabel.move 20, 20

        rotLabel = Qt::Label.new self
        rotLabel.setPixmap rotunda
        rotLabel.move 40, 160

        minLabel = Qt::Label.new self
        minLabel.setPixmap mincol
        minLabel.move 170, 50
    
    end
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In this example, we show three images using the absolute positioning.
barLabel = Qt::Label.new self
barLabel.setPixmap bardejov
The Qt::Label widget is used to hold the image.
barLabel.move 20, 20
We use the move method to position the label on the window at x=20, y=20.
When we resize the window, the labels retain their initial size.
Absolute
Figure: Absolute positioning

Buttons example

In the following example, we will position two buttons in the bottom right corner of the window.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, we use box layouts
# to position two buttons in the
# bottom right corner of the window.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Buttons"
        
        init_ui
        
        resize 330, 170
        move 300, 300

        show
    end
    
    def init_ui
        vbox = Qt::VBoxLayout.new self
        hbox = Qt::HBoxLayout.new

        ok = Qt::PushButton.new "OK", self
        apply = Qt::PushButton.new "Apply", self

        hbox.addWidget ok, 1, Qt::AlignRight
        hbox.addWidget apply

        vbox.addStretch 1
        vbox.addLayout hbox
    end
    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
We use nested box layouts to get our intended layout.
vbox = Qt::VBoxLayout.new self
hbox = Qt::HBoxLayout.new
We use one vertical and one horizontal box.
ok = Qt::PushButton.new "OK", self
apply = Qt::PushButton.new "Apply", self
These are the two buttons that will go into the bottom right corner of the window.
hbox.addWidget ok, 1, Qt::AlignRight
We put the ok button into the horizontal box. The second parameter is the stretch factor. It expands the area allotted to the ok button. It takes all available space left. The alignment of the windget inside this area is controlled by the third parameter. The Qt::AlignRight will align the button to the right.
vbox.addStretch 1
This line creates a vertically expanded white space, which will push the horizontal box with the buttons to the bottom.
vbox.addLayout hbox
The horizontal box is nested into the vertical box.
Buttons example
Figure: Buttons example

Windows example

The following is a more complicated example with nested box layouts.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, use box layouts
# to create a Windows example
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "Windows"
        
        init_ui
        
        resize 350, 300
        move 300, 300

        show
    end
    
    def init_ui
        vbox = Qt::VBoxLayout.new self

        vbox1 = Qt::VBoxLayout.new
        hbox1 = Qt::HBoxLayout.new
        hbox2 = Qt::HBoxLayout.new

        windLabel = Qt::Label.new "Windows", self
        edit = Qt::TextEdit.new self
        edit.setEnabled false

        activate = Qt::PushButton.new "Activate", self
        close = Qt::PushButton.new "Close", self
        help = Qt::PushButton.new "Help", self
        ok = Qt::PushButton.new "OK", self

        vbox.addWidget windLabel

        vbox1.addWidget activate
        vbox1.addWidget close, 0, Qt::AlignTop
        hbox1.addWidget edit
        hbox1.addLayout vbox1

        vbox.addLayout hbox1

        hbox2.addWidget help
        hbox2.addStretch 1
        hbox2.addWidget ok
        
        vbox.addLayout hbox2, 1
        setLayout vbox

    end    
end

app = Qt::Application.new ARGV
QtApp.new
app.exec
In this layout, we use two vertical and horizontal boxes.
box = Qt::VBoxLayout.new self
This is the base layout of the example.
windLabel = Qt::Label.new "Windows", self
First goes the label widget. It goes simply to the top of the vertical box.
vbox1.addWidget activate
vbox1.addWidget close, 0, Qt::AlignTop
hbox1.addWidget edit
hbox1.addLayout vbox1

vbox.addLayout hbox1
In the center part of the window we have a text edit widget and two vertically lined up buttons. The buttons go into a vertical box. The buttons are aligned to the top within this vertical box. The vertical box and the text edit go into a horizontal box. This horizontal box goes to the base vertical box, just below the label widget.
hbox2.addWidget help
hbox2.addStretch 1
hbox2.addWidget ok

vbox.addLayout hbox2, 1
The help and the ok button go into another horizontal box. There is an expanded white space between these two buttons. Again, the horizontal box goes to the base vertical box.
setLayout vbox
The base vertical box is set to be the main layout of the window.
Windows example
Figure: Windows example

New Folder example

In the last example, we use the Qt::GridLayout manager to create a New Folder layout example.
#!/usr/bin/ruby

# ZetCode Ruby Qt tutorial
#
# In this program, use the GridLayout
# to create a New Folder example.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: September 2012

require 'Qt'


class QtApp < Qt::Widget

    def initialize
        super
        
        setWindowTitle "New Folder"
        
        init_ui
        
        resize 300, 300
        move 300, 300

        show
    end
    
    def init_ui
    
        grid = Qt::GridLayout.new self

        nameLabel = Qt::Label.new "Name", self
        nameEdit = Qt::LineEdit.new self
        text = Qt::TextEdit.new self
        okButton = Qt::PushButton.new "OK", self
        closeButton = Qt::PushButton.new "Close", self

        grid.addWidget nameLabel, 0, 0
        grid.addWidget nameEdit, 0, 1, 1, 3
        grid.addWidget text, 1, 0, 2, 4
        grid.setColumnStretch 1, 1
        grid.addWidget okButton, 4, 2
        grid.addWidget closeButton, 4, 3

    end    
end

app = Qt::Application.new(ARGV)
QtApp.new
app.exec
In our example, we have one label, one line edit, one text edit and two buttons.
grid = Qt::GridLayout.new self
We create an instance of the Qt::GridLayout manager.
grid.addWidget nameLabel, 0, 0
We place the label widget in the first cell of the grid. The cells count from 0. The last two parameters are the row and column number.
grid.addWidget nameEdit, 0, 1, 1, 3
The line edit widget is placed at the first row, second column. The last two parameters are the row span and the column span. Horizontally, the widget will span three columns.
grid.setColumnStretch 1, 1
The parameters of the method are the column number and the stretch factor. Here we set stretch factor 1 to the second column. This means, that this column will take all remaining space. This was set, because we wanted our buttons to retain their initial size.
New Folder example
Figure: New Folder example
In this part of the Ruby Qt tutorial, we mentioned layout management of widgets.