PHP-GTK2 Newsletter

PHP-GTK2 Tips & Techniques
FREE Newsletter
by kksou



Sample Code 495: How to read a text file into GtkTextView?
Written by kksou   
Thursday, 15 May 2008
Problem

You want to read a text file into a GtkTextView as shown below:

How to read a text file into GtkTextView?


Solution
  • Read the entire file into a string with file_get_contents($filename).
  • Insert the text into the text buffer with GtkTextbuffer::set_text().

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

// display title
$title = new GtkLabel("Read a text file into GtkTextView");
$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);
$vbox->pack_start(new GtkLabel(), 0, 0);

// Create a new buffer and a new view to show the buffer.
$filename = $argv[0]; // note 1
$contents = file_get_contents($filename); // note 2
$buffer = new GtkTextBuffer(); // note 3
$buffer->set_text($contents); // note 4
$view = new GtkTextView(); // note 5
$view->set_buffer($buffer); // note 6
$view->set_wrap_mode(Gtk::WRAP_WORD);

  • Note that this is only 70% of the sample code. You have to be a registered member to see the entire sample code. Please login or register.
  • Registration is free and immediate.
  • Have some doubt about the registration? Please read this forum article.
Explanation
  1. Set your filename in the variable $filename. Here I just use the filename of the script you are running.
  2. Read in the entire file.
  3. Create a new text buffer.
  4. Insert the text into the text buffer.
  5. Create a new text view.
  6. Binds the text buffer to the text view.

Related Links

User reviews

There are no user reviews yet.

Note: You have to be a registered member to leave a comment. Free registration here.

 
< Prev   Next >

Copyright © 2006-2008. kksou.com. All Rights Reserved