107. How to set the button to the exact size you want - Part 3 - group of buttons?

Problem

You would like to center a group of buttons, all of size 80x32, as shown below:

How to set the button to the exact size you want - Part 3 - group of buttons?


Solution

  • Create the buttons with GtkButton.
  • Pack the buttons in a GtkHBox.
  • Create an alignment container with GtkAlignment, and set the desired x/y aligntment and x/y scale.
  • Stuff the hbox inside the aligment container.

Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
20   
21   
22   
23   
24   
25   
26   
27   
28   
29   
30   
31   
32   
33   
34   
35   
36   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 150);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Set the size of button to exactly 80 x 32\nGroup of buttons - using GtkAlignment");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0, 0);

$hbox = new GtkHBox(); // note 1

for ($i=0; $i<3; ++$i) {
    $button = new GtkButton('button '.($i+1));
    $button->set_size_request(80, 32);
    $button->connect('clicked', 'on_click');
    $hbox->pack_start($button);
    $hbox->pack_start(new GtkLabel('')); // add a small gap
}

$alignment = new GtkAlignment(0.5, 0, 0, 0);
$alignment->add($hbox);  // note 2

$vbox->pack_start($alignment); // note 3

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

function on_click($button) {
    echo "button pressed: ".$button->child->get_text()."\n";
}

?>

Output

As shown above.

 

Explanation

  1. Create the hbox to hold the buttons.
  2. Create a gtkalignment container. Here we set the x-alignment to be 0.5 to center the button.
  3. Stuff the hbox in the alignment container, and then pack the alignment container in turn in the containing vbox.

Related Links

Add comment


Security code
Refresh