Página siguiente Página anterior Índice general

23. Ficheros rc de GTK

GTK tiene su propia forma de conseguir los valores por defecto de una aplicación, y es utilizando los ficheros rc. Pueden ser utilizados para poner los colores de cualquier widget, y también pueden utilizarse para poner imágenes como fondos de algunos widgets.

23.1 Funciones para los ficheros rc

Cuando empiece su aplicación, debería incluir una llamada a:

void gtk_rc_parse( char *filename );

Poniendo el nombre del fichero de su rc. Esto hará que GTK analice este fichero, y utilice el estilo para los widgets que se definan ahí.

Si desea tener un conjunto especial de widgets con un estilo diferente de los otros, o realizar cualquier otra división lógica de los widgets, haga una llamada a:

void gtk_widget_set_name( GtkWidget *widget,
                          gchar     *name );

Pasándole su nuevo widget como primer argumento, y el nombre que desea darle como el segundo. Mediante este nombre podrá cambiar los atributos de ese widget.

Si hacemos algo así:

button = gtk_button_new_with_label ("Special Button");
gtk_widget_set_name (button, "special button");

El botón tendrá el nombre ``special button'' y podría referenciársele en el fichero rc como ``special button.GtkButton''. [<--- ˇVerificadme! ]

El fichero de ejemplo rc que mostramos a continuación, establece las propiedades de la ventana principal, y deja que todos los hijos de la ventana principal hereden el estilo descrito por ``main button''. El código utilizado en la aplicación es:

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_widget_set_name (window, "main window");

Y el estilo se define en el fichero rc utilizando:

widget "main window.*GtkButton*" style "main_button"

Qué hace que todos los widgets GtkButton de la ``main window'' (ventana principal) tengan el estilo "main_buttons" tal y como se define en el fichero rc.

Como puede ver, es un sistema muy poderoso y flexible. Utilice su imaginación para aprovecharse al máximo de este sistema.

23.2 Formato de los ficheros rc de GTK

El formato de los ficheros GTK se muestra en el ejemplo de más abajo. Éste es el fichero testgtkrc de la distribución GTK, pero he añadido unos cuantos comentarios y alguna cosilla. Puede que quiera incluir esta explicación en su aplicación para permitir al usuario personalizar su aplicación.

Hay varias directivas para cambiar los atributos de un widget.

Además de esto, hay varios estados en el que puede estar un widget, y puede especificar diferentes colores, imágenes y tipos de letra para cada estado. Estos estados son:

Cuando se utilizan las directivas ``fg'' y ``bg'' para poner los colores de los widgets, se utilizará el formato siguiente:

fg[<STATE>] = { Red, Green, Blue }

Donde STATE es uno de los estados anteriores (PRELIGHT, ACTIVE, etc...), y el Red, Green y Blue (Rojo, Verde y Azul) son valores en el rango 0 - 1.0, { 1.0, 1.0, 1.0 } es blanco. Deben estar en formato flotante, o serán un 0, por lo que "1" no funcionará, debe ser "1.0". Un "0" está bien ya que es lo mismo si no se reconoce. Los valores no reconocidos se pondrán a 0.

bg_pixmap es muy similar al de arriba, salvo que los colores se reemplazan por un nombre de fichero.

pixmap_path es una lista de los caminos (paths) separados por ``:''. Estos caminos se utilizarán para buscar cualquier imagen que indique.

La directiva sobre el tipo de letra es simplemente:

font = "<nombre del tipo de letra>"

Donde lo único difícil es saber la cadena del tipo de letra a elegir. Utilizar xfontsel o un programa similar debería ayudar.

El widget_class establece el estilo de una clase de widgets. Estas clases se muestran en el resumen de widgets dentro de la jerarquía de clases.

La directiva widget hace que un conjunto específico de widgets tenga un estido determinado, sobreescribiendo cualquier estilo anterior que tuviese esa clase de widgets. Estos widgets se registran dentro de la aplicación utilizando una llamada a gtk_widget_set_name(). Esto le permitirá especificar los atributos de un widget uno a uno, en vez de establecer los atributos de toda una clase widget. Deberá documentar cualquiera de estos widgets especiales para que los usuarios puedan personalizarlos.

Cuando la palabra clave parent se utiliza como un atributo, el widget tomará los atributos de su padre en la aplicación.

Puede asignar los atributos de un estilo previamente definido a uno nuevo.

style "main_button" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}

Este ejemplo toma el estilo ``button'', y crea un nuevo estilo ``main_button'' cambiando simplemente el tipo de letra y cambiando el color de fondo cuando el widget esté en estado PRELIGHT.

Por supuesto, muchos de estos atributos no se aplican a todos los widgets. Realmente es una cuestión de sentido común. Se utilizará cualquier atributo que se pueda aplicar.

23.3 Fichero rc de ejemplo

# pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
#
pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
#
# style <name> [= <name>]
# {
#   <option>
# }
#
# widget <widget_set> style <style_name>
# widget_class <widget_class_set> style <style_name>


# Here is a list of all the possible states.  Note that some do not apply to
# certain widgets.
#
# NORMAL - The normal state of a widget, without the mouse over top of
# it, and not being pressed etc.
#
# PRELIGHT - When the mouse is over top of the widget, colors defined
# using this state will be in effect.
#
# ACTIVE - When the widget is pressed or clicked it will be active, and
# the attributes assigned by this tag will be in effect.
#
# INSENSITIVE - When a widget is set insensitive, and cannot be
# activated, it will take these attributes.
#
# SELECTED - When an object is selected, it takes these attributes.
#
# Given these states, we can set the attributes of the widgets in each of
# these states using the following directives.
#
# fg - Sets the foreground color of a widget.
# fg - Sets the background color of a widget.
# bg_pixmap - Sets the background of a widget to a tiled pixmap.
# font - Sets the font to be used with the given widget.
#

# This sets a style called "button".  The name is not really important, as
# it is assigned to the actual widgets at the bottom of the file.

style "window"
{
  #This sets the padding around the window to the pixmap specified.
  #bg_pixmap[<STATE>] = "<pixmap filename>"
  bg_pixmap[NORMAL] = "warning.xpm"
}

style "scale"
{
  #Sets the foreground color (font color) to red when in the "NORMAL"
  #state.
  
  fg[NORMAL] = { 1.0, 0, 0 }
  
  #Sets the background pixmap of this widget to that of its parent.
  bg_pixmap[NORMAL] = "<parent>"
}

style "button"
{
  # This shows all the possible states for a button.  The only one that
  # doesn't apply is the SELECTED state.
  
  fg[PRELIGHT] = { 0, 1.0, 1.0 }
  bg[PRELIGHT] = { 0, 0, 1.0 }
  bg[ACTIVE] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 0, 1.0, 0 }
  bg[NORMAL] = { 1.0, 1.0, 0 }
  fg[NORMAL] = { .99, 0, .99 }
  bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
  fg[INSENSITIVE] = { 1.0, 0, 1.0 }
}

# In this example, we inherit the attributes of the "button" style and then
# override the font and background color when prelit to create a new
# "main_button" style.

style "main_button" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}

style "toggle_button" = "button"
{
  fg[NORMAL] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 1.0, 0, 0 }
  
  # This sets the background pixmap of the toggle_button to that of its
  # parent widget (as defined in the application).
  bg_pixmap[NORMAL] = "<parent>"
}

style "text"
{
  bg_pixmap[NORMAL] = "marble.xpm"
  fg[NORMAL] = { 1.0, 1.0, 1.0 }
}

style "ruler"
{
  font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
}

# pixmap_path "~/.pixmaps"

# These set the widget types to use the styles defined above.
# The widget types are listed in the class hierarchy, but could probably be
# just listed in this document for the users reference.

widget_class "GtkWindow" style "window"
widget_class "GtkDialog" style "window"
widget_class "GtkFileSelection" style "window"
widget_class "*Gtk*Scale" style "scale"
widget_class "*GtkCheckButton*" style "toggle_button"
widget_class "*GtkRadioButton*" style "toggle_button"
widget_class "*GtkButton*" style "button"
widget_class "*Ruler" style "ruler"
widget_class "*GtkText" style "text"

# This sets all the buttons that are children of the "main window" to
# the main_button style.  These must be documented to be taken advantage of.
widget "main window.*GtkButton*" style "main_button"


Página siguiente Página anterior Índice general