083. How to set up toolbar?

Problem

You want to set up toolbars as shown below:

How to set up toolbar?


Solution


Sample Code

1   
2   
3   
4   
5   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
20   
21   
22   
23   
24   
25   
26   
27   
29   
31   
32   
33   
34   
35   
36   
37   
39   
40   
41   
42   
45   
46   
47   
48   
49   
50   
51   
53   
55   
56   
57   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 150);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// define menu definition
$toolbar_definition = array('New', 'Open', 'Save', '<hr>', // note 1
    'Cut', 'Copy', 'Paste', '<hr>', 
    'Undo','Redo'); 
setup_toolbar($vbox, $toolbar_definition);

// display title
$title = new GtkLabel("Set up Toolbar");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$vbox->pack_start($title);
$vbox->pack_start(new GtkLabel(''));

$window->show_all();
Gtk::main();

// setup toolbar
function setup_toolbar($vbox, $toolbar_definition) { // note 1
    $toolbar = new GtkToolBar(); // note 2
    $vbox->pack_start($toolbar, 0, 0);
    foreach($toolbar_definition as $item) {
        if ($item=='<hr>') {
            $toolbar->insert(new GtkSeparatorToolItem(), -1);
        } else {
            $stock_image_name = 'Gtk::STOCK_'.strtoupper($item); // note 3
            if (defined($stock_image_name)) {
                $toolbar_item = GtkToolButton::new_from_stock( // note 4
                    constant($stock_image_name)); 
                $toolbar->insert($toolbar_item, -1); // note 5
                $toolbar_item->connect('clicked', 'on_toolbar_button', $item);
            }
        }
    }
}

// process toolbar
function on_toolbar_button($button, $item) { // note 6
    echo "toolbar clicked: $item\n";
}

?>

Output

As shown above.
 

Explanation

  1. To set up a toolbar, simply defines the $toolbar_definition and call the function setup_toolbar.
  2. Create a new toolbar.
  3. Get the stock image name from toolbar definition.
  4. Create the toolbar item.
  5. Insert into toolbar.
  6. Process toolbutton click here.

Note

You may want to compare this with the setting up of GtkMenu - How to set up menu and radio menu - Part 1?. The two are very similar.

Related Links

Add comment


Security code
Refresh