106. How to set the button to the exact size you want - Part 2 - using GtkAlignment?

Problem

Please refer to How to set the button to the exact size you want - Part 1?

This example achieves the same objective, but using GtkAlignment, as shown below:

How to set the button to the exact size you want - Part 2 - using GtkAlignment?


Solution

  • Create the button with GtkButton.
  • Create an alignment container with GtkAlignment, and set the desired x/y aligntment and x/y scale.
  • Stuff the button 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   
<?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\n   Method 2 - 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);

$button = new GtkButton('button'); // note 1
$button->set_size_request(80, 32); // note 1

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

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

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

?>

Output

As shown above.

 

Explanation

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

Notes

Note that one of the advantage of using GtkAlignment is that you can easily align the button left, right or center.

However, take note that GtkAlignment can contain only one child. So if you need to stuff more than one buttons, you have to pack the buttons inside a hbox or vbox, then stuff the hbox/vbox inside the alignement container, as explained in How to set the button to the exact size you want - Part 3 - group of buttons?

Related Links

Add comment


Security code
Refresh