Friday, September 10, 2010

GTK Programming in Ruby (2) - Adding Menubar

# menu01.rb

require 'gtk2'

class App < Gtk::Window

 def initialize
  super
  window_settings('Window with Menu', 400, 300)
  menu_settings
  event_settings
  show_all
 end
    
 def window_settings(title, width, height)
  set_title title
  set_default_size width, height
    set_window_position Gtk::Window::POS_CENTER
 end

 def menu_settings    
 
  # menu bar
  menubar = Gtk::MenuBar.new
  
  # file menu
  filemenu = Gtk::Menu.new
  filemenuitem = Gtk::MenuItem.new "File"
  filemenuitem.set_submenu filemenu
  
  # file | quit menu item
  exitmenuitem = Gtk::MenuItem.new "Quit"
  exitmenuitem.signal_connect "activate" do
    quit
  end
  filemenu.append exitmenuitem

  # edit menu
  editmenu = Gtk::Menu.new
  editmenuitem = Gtk::MenuItem.new "Edit"
  editmenuitem.set_submenu editmenu
  
  # help menu
  helpmenu = Gtk::Menu.new
  helpmenuitem = Gtk::MenuItem.new "Help"
  helpmenuitem.set_submenu helpmenu

  # append all menu(item)s to menubar
  menubar.append filemenuitem
  menubar.append editmenuitem
  menubar.append helpmenuitem
  
  # place the menu bar in the window
  vbox = Gtk::VBox.new false, 2
  vbox.pack_start menubar, false, false, 0
  add vbox
  
 end
 
 def event_settings
  signal_connect "destroy" do 
   quit
  end    
 end   
 
 def quit
  Gtk.main_quit 
 end
 
end

Gtk.init
 window = App.new
Gtk.main

Run it:
$ ruby menu01.rb

The result is:

No comments:

Post a Comment