014. How to display a list of key value pairs - Part 2?

Problem

You want to display a list of key-value pairs. In Part 1, the entire table is left aligned.

You want this table to be centered as shown below:

How to display a list of key value pairs - Part 2?


Solution

Please refer to Part 1 first.

Then use GtkHBox to centers the table.


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   
37   
38   
39   
40   
41   
42   
43   
44   
45   
<?php
$window = new GtkWindow();
$window->set_size_request(420, 175);
$window->connect_simple('destroy', array('Gtk','main_quit'));

$vbox = new GtkVBox();
$window->add($vbox);

$label = new GtkLabel();
$label->set_markup('<span color="blue" font_desc="Times New Roman Italic 12">
    Display key-value pairs - Part 2</span>');
$vbox->pack_start($label);

$table = new GtkTable();
$vbox->pack_start($hbox = new GtkHBox());
$hbox->pack_start(new GtkLabel());  // note 1
$hbox->pack_start($table, 0, 0);    // note 2
$hbox->pack_start(new GtkLabel());  // note 1

$data = array(
    'key 1' => 'value of key 1',
    'key 2' => 'value of key 2',
    'key 3' => 'value of key 3'
);

display_table ($table, $data);

function display_table($table, $list) {
    $row = 0;
    foreach($list as $k=>$v) {
        $key = new GtkLabel();
        $key->set_markup("<b>$k</b>");
        $key->set_alignment(0,0);
        $table->attach($key, 0, 1, $row, $row+1, Gtk::FILL, Gtk::SHRINK);

        $value = new GtkLabel($v);
        $value->set_alignment(0,0);
        $table->attach($value, 1, 2, $row, $row+1, Gtk::FILL, Gtk::SHRINK);
        ++$row;
    }
}

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

Output

As shown above.
 

Explanation

  1. The two lines of $hbox->pack_start(new GtkLabel()); "forces" the table to be centered.
  2. The two 0's in pack_start($table, 0, 0) is there so that PHP-GTK2 doesn't "auto-expand" the table by default.

Notes

If you omit the second $hbox->pack_start(new GtkLabel()), the table will be pushed to the right. as shown below: How to display a list of key value pairs - Part 2. fig2.

Add comment


Security code
Refresh