Home   |   Guides and Tutorials   |   What's New?   |   Comments   |   About
 

GtkText - Text Area Widget

by Brent Fox
Last Modified: Wednesday, 19-May-2004 11:54:37 EDT

Introduction
    In this example, we create a multi-line text area that the user can type in. It is possible to create a read-only text area, but the text area in this example is editable. If we added a menu bar, a toolbar, and the code to do a few basic things like opening and saving files, cutting and pasting text, and such, we'd have a very basic yet functional text editor.
Screenshot



Source Code
Source code for this example is also available in the file text.c
/*
 *File name: text.c
 */

#include <gtk/gtk.h>
#include <glib.h>

/*-- This function allows the program to exit properly when the window is closed --*/
gint destroyapp (GtkWidget *widget, gpointer gdata)
{
  g_print ("Quitting...\n");
  gtk_main_quit();
  return (FALSE);
}

int main (int argc, char *argv[])
{
  /*-- Declare the GTK Widgets used in the program --*/
  GtkWidget *window;
  GtkWidget *text;

  gchar *buffer = "This is some sample text";

  /*--  Initialize GTK --*/
  gtk_init (&argc, &argv);

  /*-- Create the new window --*/
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  /*-- Create a text area --*/
  text = gtk_text_new(NULL, NULL);

  /*-- Set text area to be editable --*/
  gtk_text_set_editable(GTK_TEXT (text), TRUE);

  /*-- Connect the window to the destroyapp function  --*/
  gtk_signal_connect(GTK_OBJECT(window), "delete_event", GTK_SIGNAL_FUNC(destroyapp), NULL);

  /*-- Add the text area to the window --*/
  gtk_container_add(GTK_CONTAINER(window), text);

  /*-- Add some text to the window --*/
  gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL, buffer, strlen(buffer));


  /*-- Set window border to zero so that text area takes up the whole window --*/
  gtk_container_border_width (GTK_CONTAINER (window), 0);

  /*-- Set the window to be 640 x 200 pixels --*/
  gtk_window_set_default_size (GTK_WINDOW(window), 640, 200);

  /*-- Set the window title --*/
  gtk_window_set_title(GTK_WINDOW (window), "Text Area");

  /*-- Display the widgets --*/
  gtk_widget_show(text);
  gtk_widget_show(window);

  /*-- Start the GTK event loop --*/
  gtk_main();

  /*-- Return 0 if exit is successful --*/
  return 0;
}
  
Compile the Source Code
gcc -Wall -g text.c -o text `gtk-config --cflags` `gtk-config --libs`

Execute the Program
./text

What's Related


All Rights Reserved Linux Headquarters © 2000-2007
Linux is a registered trademark of Linus Torvalds
All logos are registered trademarks of their respective owners
Last modified: Wednesday, May 19, 2004