7.4. Radio Buttons

Radio buttons are similar to check buttons except they are grouped so that only one may be selected/depressed at a time. This is good for places in your application where you need to select from a short list of options.

Creating a new radio button is done with one of these calls:

Gtk::RadioButton.new
Gtk::RadioButton.new( label, use_underline )
Gtk::RadioButton.new( stockitem )
Gtk::RadioButton.new( label )
Gtk::RadioButton.new( group, label, use_underline )
Gtk::RadioButton.new( group, stockitem )

You'll notice the argument to these calls. They require a group to perform thier duty properly. You can add a radio button to a group in a couple of different ways. Look at the example code given below for the various ways to do it. You will also notice the arguments stockitem and use_underline. The first argument is used to create a stock image and text that is built into GTK itself, and it accepts a Gtk::Stock item. The second argument is use_underline, which sets up a mnemonic

The important thing to remember is to add each new button to the group, with the primary (first) button passed as the argument. This allows a chain of buttons to be established. The example below should make this clear.

require 'gtk2'

def close_application( widget, event )
   Gtk.main_quit
   return false
end

Gtk.init
window = Gtk::Window.new( Gtk::Window::TOPLEVEL )
window.signal_connect( "delete_event" ) { |w,e| close_application( w, e ) }
window.title=( "Radio Buttons" )
window.border_width=( 0 )

box1 = Gtk::VBox.new( false, 0 )
window.add( box1 )

box2 = Gtk::VBox.new( false, 10 )
box2.border_width=( 10 )
box1.pack_start( box2, true, true, 0 )

# A normal radio button
button = Gtk::RadioButton.new( "Button1" )
box2.pack_start( button, true, true, 0 )

# Use underline
button = Gtk::RadioButton.new( button, "_Button2", true )
button.active=( true )
box2.pack_start( button, true, true, 0 )

# Don;t use underline
button = Gtk::RadioButton.new( button, "_Button3", false )
box2.pack_start( button, true, true, 0 )

# Use a stock item
button = Gtk::RadioButton.new( button, Gtk::Stock::YES )
box2.pack_start( button, true, true, 0 )

separator = Gtk::HSeparator.new
box1.pack_start( separator, false, true, 0 )

button = Gtk::Button.new( Gtk::Stock::QUIT )
button.signal_connect( "clicked" ) { |w| close_application( w, nil ) }
box1.pack_start( button, true, true, 0 )
button.can_default=( true )
button.grab_default

window.show_all
Gtk.main

Prev Next