004. How to change the font and font size of GtkLabel?

Problem

You want to change the font and font size of GtkLabel as shown below:

How to change the font and font size of GtkLabel?


Solution

Use GtkWidget::modify_font()

$label->modify_font(new PangoFontDescription('Eras Demi ITC 48'));

Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
<?php
$window = new GtkWindow();
$window->set_size_request(480, 240);
$window->modify_bg(Gtk::STATE_NORMAL, GdkColor::parse("#FFFF00"));
$window->connect_simple('destroy', array('Gtk','main_quit'));
$label = new GtkLabel("hello world!");
$label->modify_font(new PangoFontDescription('Eras Demi ITC 48')); // set font style
$window->add($label);
$window->show_all();
Gtk::main();
?>

Output

As shown above.
 

Explanation

  • The line with modify_font() sets the font of the label to "Eras Demi ITC" and font size to 48.
  • You can just change the font size, without specifying the font name, e.g. modify_font(new PangoFontDescription('48'))
  • I'm using php-gtk2 on winXP. For windows, you can get the names of the fonts in the fonts directory (usually it's c:\windows\fonts). E.g. you can use 'Times New Roman', 'Times New Roman Italic', 'Tahoma', 'Trebuchet MS Bold', etc. Just use the font names as it appears in that folder.
  • I think it should be quite similar for Linux and Mac. If you're on this platform, maybe you could let me know if it works.

Add comment


Security code
Refresh