Problem
You want to display a list of key-value pairs as shown below:
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 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 46 | <?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>"); $key->set_alignment(0,0); // note 3 $table->attach($key, 0, 1, $row, $row+1, Gtk::FILL, Gtk::SHRINK); // note 4 $value = new GtkLabel($v); $value->set_alignment(0,0); $table->attach($value, 1, 2, $row, $row+1, Gtk::FILL, Gtk::SHRINK); // note 4 ++$row; } } $window->show_all(); Gtk::main(); ?> |
Output
As shown above.Explanation
- 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. - Too lazy to write a whole bunch of
GtkTable::attach
statements. So wrote a small function for this. - 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.
- Put the contents in the respective cell with GtkTable::attach().
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:
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
Read more...