Sample Code 13: How to display a list of key value pairs - Part 1?
Written by kksou   
Thursday, 14 September 2006
Problem

You want to display a list of key-value pairs as shown below:

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


Solution

Use GtkTable

Put the keys in column 1, and the values in column2

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   
<?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 1</span>');
$vbox->pack_start($label);

$table = new GtkTable(); // note 1
$vbox->pack_start($table);

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

display_table ($table, $data); // note 2

function display_table($table, $list) {
    $row = 0;
    foreach($list as $k=>$v) {
        $key = new GtkLabel();
        $key->set_markup("<b>$k</b>");
  • Note that this is only 70% of the sample code. You have to be a registered member to see the entire sample code. Please login or register.
  • Registration is free and immediate.
  • Have some doubt about the registration? Please read this forum article.
Explanation
  1. When you create a table with new GtkTable, it is not necessary to define the number of rows and columns. Tables are dynamic in PHP-GTK2, i.e. you can add any number of columns and rows on the fly in your program.
  2. Too lazy to write a whole bunch of GtkTable::attach statements. So wrote a small function for this.
  3. Align the label to the left. You may want to refer to How to left or right align GtkLabel in GtkWindow for more information about label alignment.
  4. Put the contents in the respective cell with GtkTable::attach().
  5. Note the use of Gtk::FILL, Gtk::SHRINK. Try it. If you don't specify these two values, the two labels will be spaced out apart (both in the x and y directions), as shown below:

    How to display a list of key value pairs - Part 1. fig2


Note

Note that the table is aligned to the left. If you wish to have the table centered (as shown below), pleae refer to Part 2

How to display a list of key value pairs - Part 1. fig3