200. How to set GtkTextView to look like GtkLabel?

Problem

A standard GtkTextView has a white background as shown below:

You would like to set the background color of the GtkTextView to the default gray color of the window so that the GtkTextView looks like a GtkLabel as shown below:

How to set GtkTextView to look like GtkLabel?


Solution


Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
16   
17   
18   
19   
20   
22   
23   
24   
25   
26   
27   
28   
29   
30   
31   
32   
33   
34   
35   
36   
37   
38   
40   
41   
42   
43   
44   
45   
<?php
$window = &new GtkWindow();
$window->connect_simple('destroy', array( 'Gtk', 'main_quit'));
$window->set_size_request(400,200);
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Set bg color of textview to default bg color");
$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);
$title->set_justify(Gtk::JUSTIFY_CENTER);
$alignment = new GtkAlignment(0.5, 0, 0, 0);
$alignment->add($title);
$vbox->pack_start($alignment, 0, 0);
$vbox->pack_start(new GtkLabel(), 0, 0);

$window->realize(); // note 1
$org_bg = $window->get_style()->bg[Gtk::STATE_NORMAL]; // note 2

// setup textview and textbuffer
$buffer = new GtkTextBuffer();
$view = new GtkTextView();
$view->set_buffer($buffer);
$view->modify_font(new PangoFontDescription("Arial 12"));
$view->set_wrap_mode(Gtk::WRAP_WORD);

$scrolled_win = new GtkScrolledWindow();
$scrolled_win->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
$scrolled_win->add($view);

$vbox->pack_start($scrolled_win);

$buffer->set_text("This is a GtkTextView\n".
"disguised as a GtkLabel by setting ".
"the bg color to be the default gray of the window");
$view->modify_base(Gtk::STATE_NORMAL, $org_bg); // note 3

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

?>

Output

As shown above.

 

Explanation

  1. Remember to realize the window before making a copy of the original background color. Try commenting this line out and you will find that you won't get the original color.
  2. Make a copy of the original background color.
  3. Set the GtkTextView to the default gray, making it look like a GtkLabel.

Note

Note that we make use of exactly the same technique as we have used in How to set the background to original default color?

Related Links

Add comment


Security code
Refresh