006. How to place a background image in GtkWindow?

Problem

You want to place a background image in a GtkWindow as shown below:

How to place a background image in GtkWindow?


Solution

  • Load the image with GdkPixbuf::new_from_file().
  • Get the corresponding pixmap using GdkPixbuf::render_pixmap_and_mask().
  • Get the GtkStyle corresponding to the window with GtkWidget::get_style().
  • Set the new style with GtkWidget::set_style().

Sample Code

The following image file (sample6.png) is required by the sample code below. Please save a copy of the image file and put it in the same directory where you store the sample code.

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
20   
<?php
$window = new GtkWindow();
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->set_size_request(480, 240);

// set background image
$pixbuf=GdkPixbuf::new_from_file("sample6.png"); // note 1
list($pixmap,$mask)=$pixbuf-> render_pixmap_and_mask(255); // note 2
$style = $window->get_style(); // note 3
$style=$style->copy(); // note 4
$style->bg_pixmap[Gtk::STATE_NORMAL]=$pixmap; // note 5
$window->set_style($style); // note 6

// prints hello world
$label = new GtkLabel("hello world!");
$window->add($label);

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

Output

As shown above.
 

Comments   

+1 # Kamil 2012-01-21 15:15
It's very helpfull :) Thank you :)
Reply | Reply with quote | Quote
+1 # chachkalica 2012-03-02 03:57
great! tnx!
loaded the image from a custom folder e.g. images/
finally I'm getting the hang of php gtk tnx to your tutorials! good job man! :]
Reply | Reply with quote | Quote
+1 # atmoner 2012-11-20 15:29
nice code! thx a lot :-*
Reply | Reply with quote | Quote

Add comment


Security code
Refresh