009. How to put a border around GtkLabel?

Problem

You want to achieve the following:

How to put a border around GtkLabel?


Solution

  • Create a GtkFrame
  • Place the label in the frame
  • Set the background color of the frame with modify_bg which will become the color of the border

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   
<?php
$window = &new GtkWindow();
$window->connect_simple('destroy', array( 'Gtk', 'main_quit'));
$window->set_size_request(400,200);

// create a vbox to hold multiple labels
$vbox = new GtkVBox();

$frame = new GtkFrame();
$frame->modify_bg(Gtk::STATE_NORMAL, GdkColor::parse('#0000ff')); // note 1

// create the title label and stuff it in the eventbox
$title = new GtkLabel('This is the title');
$title->set_size_request(100,48);
$frame->add($title);
$vbox->pack_start($frame, 0, 0); // note 2

// create the body_text and place it below the title
$label2 = new GtkLabel('This is the body text');
$vbox->pack_start($label2); // note 3

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

Output

As shown above.
 

Explanation

You can add a border to GtkLabel with GtkFrame.

Note 1: this sets the color of the border. Note the use of modify_bg and not modify_fg.

Note 2: this make sure that php-gtk doesn't change the size of title.

Note 3: this makes the body text stretechable, that is, it will take on whatever space remains below the title.

You may want to compare this with setting background color of GtkLabel. The concept is exactly the same, except a border uses GtkFrame, and setting background color uses eventbox.

 

Add comment


Security code
Refresh