10.13. File Selections

The file selection widget is a quick way to display a File dialog box. It comes complete with Ok, Cancel, and Help buttons, a great way to cut down on programming time.

To create a new file selection box, use:

Gtk::FileSelection.new( title )

To set the filename, for example to bring up a specific directory or give a default filename, use these methods:

Gtk::FileSelection#set_filename( filename )
Gtk::FileSelection#filename=( filename )

To grab the text that the user has has entered or clicked on, use this method:

Gtk::FileSelection#filename

There are also widgets you can access within the file selection widget by using these methods:

Gtk::FileSelection#dir_list
Gtk::FileSelection#file_list
Gtk::FileSelection#selection_entry
Gtk::FileSelection#selection_text
Gtk::FileSelection#main_vbox
Gtk::FileSelection#ok_button
Gtk::FileSelection#cancel_button
Gtk::FileSelection#help_button

Most likely you will want to use th ok_button, cancel_button, and help_button in signaling thier use.

Included here is an example ported to Ruby-GNOME2 from the GTK C tutorial. As you will see, there is nothing much to creating a file selection widget. While this example the help button appears on the screen, it does nothing as there is not signal attached to it.

require 'gtk2'

def file_ok_sel( w, fs )
   puts fs.filename
end

Gtk.init

# Create a new fileselection widget
filew = Gtk::FileSelection.new( "File Selection" )

filew.signal_connect( "destroy" ) { Gtk.main_quit }

# Connect the ok_button to file_ok_sel method
filew.ok_button.signal_connect( "clicked" ) { |w| file_ok_sel( w, filew ) }

# Connect the cancel_button to destroy the widget
filew.cancel_button.signal_connect( "clicked" ) { Gtk.main_quit }

# Lets set the filename, as if this were a save dialog, and we are giving
# a default filename
filew.filename=( "penguin.png" )

filew.show
Gtk.main

Prev Next