019. How to display a 2D array in table - Part 2?

Problem

We have displayed a 2D array in a table in Part 1. Now we would like to add borders to the table as shown below:

$data = array(
array('', 'header1', 'header2', 'header3'),
array('row0', 1, 2, 3),
array('row1', 4, 5, 6));

How to display a 2D array in table - Part 2?


Solution

  • GtkTable itself does not provide built-in method such as the <table border=1> statement in html to add a border to each cell.
  • However, the GtkTable::attach() method allows us to attach almost any widget to each cell.
  • As such, to draw a border, we simply put each cell inside a GtkFrame, and attach the GtkFrame to 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   
26   
27   
28   
29   
31   
32   
34   
35   
36   
37   
38   
39   
40   
41   
42   
43   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 200);
$window->connect_simple('destroy', array('Gtk','main_quit'));

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

// display title
$title = new GtkLabel('Display 2D Array in Table - Part 2 (add borders)');
$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);

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

$data = array(
array('', 'header1', 'header2', 'header3'),
array('row0', 1, 2, 3),
array('row1', 4, 5, 6));

display_table ($table, $data);

function display_table($table, $a) {
    for ($row=0; $row<count($a); ++$row) {
        for ($col=0; $col<count($a[$row]); ++$col) {
            $frame = new GtkFrame(); // note1
            $frame->add(new GtkLabel($a[$row][$col])); // note 2
            $table->attach($frame, $col, $col+1, $row, $row+1); // note3
        }
    }
}

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

Output

As shown above.
 

Explanation

Please refer to Part 1 first which explains how to display a 2D array in a table.

What's new here in Part 2:

  1. Create the frame
  2. Put the cell content (GtkLabel) inside the frame
  3. Attach the frame (not the GtkLabel) to the table
And you now have a table with borders!

Add comment


Security code
Refresh