108. How to align GtkEntry fields - Part 1?

Problem

If you align GtkEntry using just "plain" GtkTable, you will find that the field labels on the left get "centered":

Suppose you would like to display the field labels "more professionally" as shown below:

How to align GtkEntry fields - Part 1?


Solution

We make use of the method as outlined in How to set the button to the exact size you want - Part 2 - using GtkAlignment?, that is, with the use of GtkAlignment.


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   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
42   
44   
45   
46   
47   
48   
49   
50   
51   
52   
53   
54   
55   
56   
57   
58   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 240);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Align GtkEntry Fields - Part 1");
$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);

$fields = array('Item number', 'Item Description', 'Unit price', 'Quantity');
$entry = array(); // to store the text entries

$table = new GtkTable();
display_table($table, $fields); // display the table
$vbox->pack_start($table);

function display_table($table, $fields) {
    global $entry;
    $row = 0;
    foreach ($fields as $field) {
        $label = new GtkLabel("$field: ");
        $entry[$row] = new GtkEntry();
        $alignment = new GtkAlignment(1, .5, 0, 0); // note 1
        $alignment->add($label);
        $table->attach($alignment, 0, 1, $row, $row+1);
        $table->attach($entry[$row], 1, 2, $row, $row+1);
        ++$row;
    }
}

// create a submit button
$button = new GtkButton('Submit');
$button->set_size_request(60, 28);
$button->connect('clicked', 'on_click');
$row = count($fields);
$alignment = new GtkAlignment(0, 0.5, 0, 0); // note 2
$alignment->add($button);
$table->attach($alignment, 1, 2, $row, $row+1);

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

function on_click($button) {
    global $fields, $entry;
    $i=0;
    foreach($fields as $field) {
        echo "$field: ".$entry[$i]->get_text()."\n";
        ++$i;
    }
}

?>

Output

As shown above.

 

Explanation

  1. Align the field label to the right of column 0, and set valign=middle.
  2. Align the button to the left of column 1, and set valign=middle.

Related Links

Add comment


Security code
Refresh