Blame platform-demos/es/treeview_simple_liststore.js.page

Packit 1470ea
Packit 1470ea
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:xi="http://www.w3.org/2001/XInclude" type="guide" style="task" id="treeview_simple_liststore.js" xml:lang="es">
Packit 1470ea
  <info>
Packit 1470ea
  <title type="text">TreeView con ListStore (JavaScript)</title>
Packit 1470ea
    <link type="guide" xref="beginner.js#treeview"/>
Packit 1470ea
    <link type="seealso" xref="GtkApplicationWindow.js"/>
Packit 1470ea
    <link type="seealso" xref="grid.js"/>
Packit 1470ea
    <link type="seealso" xref="label.js"/>
Packit 1470ea
    <revision version="0.1" date="2012-07-04" status="draft"/>
Packit 1470ea
Packit 1470ea
    <credit type="author copyright">
Packit 1470ea
      <name>Taryn Fox</name>
Packit 1470ea
      <email its:translate="no">jewelfox@fursona.net</email>
Packit 1470ea
      <years>2012</years>
Packit 1470ea
    </credit>
Packit 1470ea
Packit 1470ea
    <desc>Un widget que muestra una lista separada de elementos</desc>
Packit 1470ea
  
Packit 1470ea
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
Packit 1470ea
      <mal:name>Daniel Mustieles</mal:name>
Packit 1470ea
      <mal:email>daniel.mustieles@gmail.com</mal:email>
Packit 1470ea
      <mal:years>2011 - 2017</mal:years>
Packit 1470ea
    </mal:credit>
Packit 1470ea
  
Packit 1470ea
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
Packit 1470ea
      <mal:name>Nicolás Satragno</mal:name>
Packit 1470ea
      <mal:email>nsatragno@gmail.com</mal:email>
Packit 1470ea
      <mal:years>2012 - 2013</mal:years>
Packit 1470ea
    </mal:credit>
Packit 1470ea
  
Packit 1470ea
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
Packit 1470ea
      <mal:name>Jorge González</mal:name>
Packit 1470ea
      <mal:email>jorgegonz@svn.gnome.org</mal:email>
Packit 1470ea
      <mal:years>2011</mal:years>
Packit 1470ea
    </mal:credit>
Packit 1470ea
  </info>
Packit 1470ea
Packit 1470ea
  <title>TreeView con ListStore</title>
Packit 1470ea
  <media type="image" mime="image/png" src="media/treeview_simple_liststore_penguins.png"/>
Packit 1470ea
  

Un TreeView es como una ventana sobre los contenidos de un ListStore o un TreeStore. Un ListStore es como una hoja de cálculo: una lista de cosas «plana», de dos dimensiones, dividida en filas y columnas. Un TreeStore, en cambio, puede bifurcarse en distintas direcciones como un árbol. En este ejemplo, se crea un TreeView que muestra el contenido de un ListStore con nombres y números de teléfono (ficticios), y se configura para que la <link xref="label.js">Etiqueta</link> en la parte inferior de la ventana muestre más información acerca de cualquier nombre en el que pulse.

Packit 1470ea
  

Un TreeView no es solamente un widget individual, sino que contiene varios más pequeños.

Packit 1470ea
  <list>
Packit 1470ea
    <item>

Los widgets TreeViewColumn muestran cada columna (vertical) de información del ListStore. Cada uno tiene un título que puede mostrarse en la parte superior de la columna, como en la captura de pantalla.

</item>
Packit 1470ea
    <item>

Los widgets CellRenderer se «empaquetan» en cada TreeViewColumn, y contienen las instrucciones de cómo mostrar cada «celda» individual, o elemento del ListStore. Hay varios tipos diferentes, incluyendo el CellRendererText que se usa aquí y el CellRendererPixbuf, que muestra una imagen («búfer de píxeles»).

</item>
Packit 1470ea
  </list>
Packit 1470ea
  

Finalmente, se usará un objeto llamado TreeIter, que no es un widget sino un cursor invisible que apunta a una fila (horizontal) en el ListStore. Cada vez que pulsa en un nombre en la libreta de direcciones, por ejemplo, se crea un TreeIter apuntando a la fila seleccionada, y después se usa para decirle al ListStore el elemento del que tiene que mostrar más información.

Packit 1470ea
  <note>

El TreeView es probablemente el widget de GTK más complicado, por la cantidad de partes que tiene y por cómo tienen que trabajar juntas. Tómese un tiempo para aprender cómo funciona y experimentar con él, o intente algo más fácil primero si encuentra problemas.

</note>
Packit 1470ea
    <links type="section"/>
Packit 1470ea
Packit 1470ea
  <section id="imports">
Packit 1470ea
    <title>Bibliotecas que importar</title>
Packit 1470ea
    
Packit 1470ea
#!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
const GObject = imports.gi.GObject;
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
const Lang = imports.lang;
Packit 1470ea
const Pango = imports.gi.Pango;
Packit 1470ea
Packit 1470ea
    

Estas son las bibliotecas que necesita importar para que esta aplicación se ejecute. Recuerde que la línea que le dice a GNOME que está usando Gjs siempre tiene que ir al principio.

Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="applicationwindow">
Packit 1470ea
    <title>Crear la ventana de la aplicación</title>
Packit 1470ea
    
Packit 1470ea
const TreeViewExample = new Lang.Class({
Packit 1470ea
    Name: 'TreeView Example with Simple ListStore',
Packit 1470ea
Packit 1470ea
    // Create the application itself
Packit 1470ea
    _init: function() {
Packit 1470ea
        this.application = new Gtk.Application({
Packit 1470ea
            application_id: 'org.example.jstreeviewsimpleliststore'
Packit 1470ea
        });
Packit 1470ea
Packit 1470ea
    // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
    this.application.connect('activate', Lang.bind(this, this._onActivate));
Packit 1470ea
    this.application.connect('startup', Lang.bind(this, this._onStartup));
Packit 1470ea
    },
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate: function() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    },
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup: function() {
Packit 1470ea
        this._buildUI ();
Packit 1470ea
    },
Packit 1470ea
Packit 1470ea
    

Todo el código de este ejemplo va en la clase TreeViewExample. El código anterior crea una <link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link> en la que van los widgets y la ventana.

Packit 1470ea
    
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI: function() {
Packit 1470ea
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 250,
Packit 1470ea
            default_width: 100,
Packit 1470ea
            border_width: 20,
Packit 1470ea
            title: "My Phone Book"});
Packit 1470ea
Packit 1470ea
    

La función _buildUI es donde se pone todo el código que crea la interfaz de usuario de la aplicación. El primer paso es crear una <link xref="GtkApplicationWindow.js">Gtk.ApplicationWindow</link> nueva para poner dentro todos los widgets.

Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="liststore">
Packit 1470ea
    <title>Crear el ListStore</title>
Packit 1470ea
    
Packit 1470ea
        // Create the underlying liststore for the phonebook
Packit 1470ea
        this._listStore = new Gtk.ListStore ();
Packit 1470ea
        this._listStore.set_column_types ([
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING]);
Packit 1470ea
Packit 1470ea
    

Primero se crea el ListStore como cualquier otro widget. Después se llama a su método set_column_types, y se le pasa una matriz de tipos de datos GObject (se podrían haber puesto todos los tipos en una sola línea, pero aquí se separan para hacerlo más fácil de leer).

Packit 1470ea
    

Los tipos de datos GObject que puede usar incluyen:

Packit 1470ea
    <list>
Packit 1470ea
      <item>

<file>GObject.TYPE_BOOLEAN</file>: verdadero o falso

</item>
Packit 1470ea
      <item>

<file>GObject.TYPE_FLOAT</file>: un número de coma flotante (uno con coma decimal)

</item>
Packit 1470ea
      <item>

<file>GObject.TYPE_STRING</file>: una cadena de letras y números

</item>
Packit 1470ea
      <item>

<file>gtk.gdk.Pixbuf</file>: una imagen

</item>
Packit 1470ea
    </list>
Packit 1470ea
    

En este caso, se está haciendo un ListStore de cuatro columnas, cada una conteniendo valores de cadenas.

Packit 1470ea
    <note>

Necesita poner la línea <file>const GObject = imports.gi.GObject;</file> al principio del código de su aplicación, como se hizo en este ejemplo, si quiere poder usar tipos de GObject.

</note>
Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        // Data to go in the phonebook
Packit 1470ea
        this.phonebook =
Packit 1470ea
        let phonebook =
Packit 1470ea
            [{ name: "Jurg", surname: "Billeter", phone: "555-0123",
Packit 1470ea
                description: "A friendly person."},
Packit 1470ea
             { name: "Johannes", surname: "Schmid", phone: "555-1234",
Packit 1470ea
                description: "Easy phone number to remember."},
Packit 1470ea
             { name: "Julita", surname: "Inca", phone: "555-2345",
Packit 1470ea
                description: "Another friendly person."},
Packit 1470ea
             { name: "Javier", surname: "Jardon", phone: "555-3456",
Packit 1470ea
                description: "Bring fish for his penguins."},
Packit 1470ea
             { name: "Jason", surname: "Clinton", phone: "555-4567",
Packit 1470ea
                description: "His cake's not a lie."},
Packit 1470ea
             { name: "Random J.", surname: "Hacker", phone: "555-5678",
Packit 1470ea
                description: "Very random!"}];
Packit 1470ea
Packit 1470ea
    

Aquí se tiene la información que va en el ListStore. Es una matriz de objetos, cada uno correspondiente a una única entrada en la libreta de direcciones.

Packit 1470ea
    

Tenga en cuenta que el TreeView en la captura de pantalla no muestra en realidad los datos de las propiedades «description». En su lugar, esa información se muestra en la etiqueta debajo, para cada fila en la que pulse. Eso es así porque el TreeView y el ListStore son dos cosas separadas, y un TreeView puede mostrar todo o parte de un ListStore, y mostrar su información de maneras diferentes. Puede hacer que varios widgets muestren cosas del mismo ListStore, como la etiqueta del ejemplo, o incluso un segundo TreeView.

Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        for (i = 0; i < phonebook.length; i++ ) {
Packit 1470ea
            let contact = phonebook [i];
Packit 1470ea
            this._listStore.set (this._listStore.append(), [0, 1, 2, 3],
Packit 1470ea
                [contact.name, contact.surname, contact.phone, contact.description]);
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
    

Este bucle <file>for</file> pone las cadenas de la libreta de direcciones en el ListStore ordenadas. En orden, se le pasa al método «set» del ListStore el iter que apunta a la fila correcta, una matriz que dice qué columnas se quieren establecer, y una matriz que contiene los datos que se quieren poner en esas columnas.

Packit 1470ea
    

Un método <file>append</file> del ListStore le añade una fila horizontal (empieza sin ninguna), y devuelve un TreeIter apuntando a esa fila como un cursor. Entonces, pasándole <file>this._listStore.append()</file> al ListStore como una propiedad, se está creando una fila nueva y diciéndole al método <file>set</file> en qué fila tiene que establecer los datos al mismo tiempo.

Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="treeview">
Packit 1470ea
    <title>Crear el TreeView</title>
Packit 1470ea
    
Packit 1470ea
        // Create the treeview
Packit 1470ea
        this._treeView = new Gtk.TreeView ({
Packit 1470ea
            expand: true,
Packit 1470ea
            model: this._listStore });
Packit 1470ea
Packit 1470ea
    

Aquí se crea un widget TreeView básico, que se expande tanto horizontal como verticalmente para usar tanto espacio como se necesite. Se configura para usar el ListStore que se creó como su «modelo», o aquello desde donde mostrará datos.

Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        // Create the columns for the address book
Packit 1470ea
        let firstName = new Gtk.TreeViewColumn ({ title: "First Name" });
Packit 1470ea
        let lastName = new Gtk.TreeViewColumn ({ title: "Last Name" });
Packit 1470ea
        let phone = new Gtk.TreeViewColumn ({ title: "Phone Number" });
Packit 1470ea
Packit 1470ea
    

Ahora se crean todas las TreeViewColumns verticales que se verán en el TreeView. El título de cada una va en la parte superior, como puede ver en la captura de pantalla.

Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        // Create a cell renderer for when bold text is needed
Packit 1470ea
        let bold = new Gtk.CellRendererText ({
Packit 1470ea
            weight: Pango.Weight.BOLD });
Packit 1470ea
Packit 1470ea
        // Create a cell renderer for normal text
Packit 1470ea
        let normal = new Gtk.CellRendererText ();
Packit 1470ea
Packit 1470ea
        // Pack the cell renderers into the columns
Packit 1470ea
        firstName.pack_start (bold, true);
Packit 1470ea
        lastName.pack_start (normal, true);
Packit 1470ea
        phone.pack_start (normal, true);
Packit 1470ea
Packit 1470ea
    

Aquí se crean los CellRenderer que se usarán para mostrar el texto del ListStore, y se empaquetan en las TreeViewColumn. Cada CellRendererText se usa para todas las entradas en esa columna. El CellRendererText normal sólo crea texto plano, mientras que el «bold» usa texto en negrita. Se pone en la primera columna de nombre, y se le dice a las otras dos que usen copias de la normal. El «true» usado como segundo parámetro para el método <file>pack_start</file> le dice que expanda las celdas cuando sea posible, en lugar de mantenerlas compactas.

Packit 1470ea
    <note>

<link href="http://www.pygtk.org/docs/pygtk/pango-constants.html">Aquí hay una lista</link> de otras propiedades de texto que puede usar. Para usar estas constantes de Pango, asegúrese de poner la línea <file>const Pango = imports.gi.Pango;</file> al principio del código como se hizo.

</note>
Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        firstName.add_attribute (bold, "text", 0);
Packit 1470ea
        lastName.add_attribute (normal, "text", 1);
Packit 1470ea
        phone.add_attribute (normal, "text", 2);
Packit 1470ea
Packit 1470ea
        // Insert the columns into the treeview
Packit 1470ea
        this._treeView.insert_column (firstName, 0);
Packit 1470ea
        this._treeView.insert_column (lastName, 1);
Packit 1470ea
        this._treeView.insert_column (phone, 2);
Packit 1470ea
Packit 1470ea
    

Ahora que se han puesto los CellRenderer en las TreeViewColumn, se usa el método <file>add_attribute</file> para decirle a cada columna que obtenga texto del modelo que el TreeView está configurado para usar; en este caso, el ListStore con la libreta de direcciones.

Packit 1470ea
    <list>
Packit 1470ea
      <item>

El primer parámetro es qué CellRenderer se usará para procesar lo que se está obteniendo.

</item>
Packit 1470ea
      <item>

El segundo parámetro es qué tipo de información se obtendrá. En este caso, se le está haciendo saber que se procesa texto.

</item>
Packit 1470ea
      <item>

El tercer parámetro es de cuál de las columnas del ListStore se está obteniendo la información.

</item>
Packit 1470ea
    </list>
Packit 1470ea
    

Después de haber preparado eso, se usa el método <file>insert_column</file> del TreeView para poner dentro las TreeViewColumn en orden. El TreeView ahora está terminado.

Packit 1470ea
    <note>

Normalmente, usaría un bucle para inicializar su TreeView, pero en este ejemplo se hacen las cosas paso a paso para hacerlo más fácil de entender.

</note>
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="ui">
Packit 1470ea
    <title>Crear el resto de la IU</title>
Packit 1470ea
    
Packit 1470ea
        // Create the label that shows details for the name you select
Packit 1470ea
        this._label = new Gtk.Label ({ label: "" });
Packit 1470ea
Packit 1470ea
        // Get which item is selected
Packit 1470ea
        this.selection = this._treeView.get_selection();
Packit 1470ea
Packit 1470ea
        // When something new is selected, call _on_changed
Packit 1470ea
        this.selection.connect ('changed', Lang.bind (this, this._onSelectionChanged));
Packit 1470ea
Packit 1470ea
    

El método <file>get_selection</file> del TreeView devuelve un objeto llamado TreeSelection. Una TreeSelection es como un TreeIter en el sentido de que es básicamente un cursor que apunta a una fila particular, excepto que apunta a la que está resaltada visiblemente como seleccionada.

Packit 1470ea
    

Después de obtener la TreeSelection que va con el TreeView, le pedimos que nos diga cuándo cambia la fila a la que está apuntando. Esto se hace conectando la señal <file>changed</file> a la función «_onSelectionChanged» que se escribió. Esta función cambia el texto que muestra la etiqueta que se acaba de hacer.

Packit 1470ea
Packit 1470ea
    
Packit 1470ea
        // Create a grid to organize everything in
Packit 1470ea
        this._grid = new Gtk.Grid;
Packit 1470ea
Packit 1470ea
        // Attach the treeview and label to the grid
Packit 1470ea
        this._grid.attach (this._treeView, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._label, 0, 1, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
    },
Packit 1470ea
Packit 1470ea
    

Después de haber terminado eso, se crea una <link xref="grid.js">Rejilla</link> para poner todo dentro, se añade a la ventana y se le dice a esta que se muestre y revele su contenido.

Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="function">
Packit 1470ea
    <title>Función que maneja una selección cambiada</title>
Packit 1470ea
Packit 1470ea
    
Packit 1470ea
    _onSelectionChanged: function () {
Packit 1470ea
Packit 1470ea
        // Grab a treeiter pointing to the current selection
Packit 1470ea
        let [ isSelected, model, iter ] = this.selection.get_selected();
Packit 1470ea
Packit 1470ea
        // Set the label to read off the values stored in the current selection
Packit 1470ea
        this._label.set_label ("\n" +
Packit 1470ea
            this._listStore.get_value (iter, 0) + " " +
Packit 1470ea
            this._listStore.get_value (iter, 1) + " " +
Packit 1470ea
            this._listStore.get_value (iter, 2) + "\n" +
Packit 1470ea
            this._listStore.get_value (iter, 3));
Packit 1470ea
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
});
Packit 1470ea
Packit 1470ea
    

La línea de código con la declaración let es un poco compleja, pero sin embargo es la mejor manera de hacer que un TreeIter apunte a la misma fila que la TreeSelection. Tiene que crear un par de referencias a otros objetos, pero <file>iter</file> es la única que se necesita.

Packit 1470ea
    

Después de haber hecho eso, se llama a la función <file>set_label</file> de la etiqueta, y se usa la función <file>get_value</file> del ListStore algunas veces para llenar los datos que queremos poner en ella. Sus parámetros son un TreeIter apuntando a la fila de la que queremos obtener los datos, y la columna.

Packit 1470ea
    

Aquí, se quieren obtener datos de todas las cuatro columnas, incluyendo la «escondida» que no es parte del TreeView. De esta manera, se puede usar la etiqueta para mostrar cadenas que son demasiado largas para entrar en el TreeView, y que no necesitamos ver de un vistazo.

Packit 1470ea
Packit 1470ea
    
Packit 1470ea
// Run the application
Packit 1470ea
let app = new TreeViewExample ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
    

Finalmente, se crea una instancia nueva de la clase TreeViewExample terminada, y se ejecuta la aplicación.

Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="complete">
Packit 1470ea
    <title>Código de ejemplo completo</title>
Packit 1470ea
#!/usr/bin/gjs
Packit 1470ea
Packit 1470ea
imports.gi.versions.Gtk = '3.0';
Packit 1470ea
Packit 1470ea
const GObject = imports.gi.GObject;
Packit 1470ea
const Gtk = imports.gi.Gtk;
Packit 1470ea
const Pango = imports.gi.Pango;
Packit 1470ea
Packit 1470ea
class TreeViewExample {
Packit 1470ea
    // Create the application itself
Packit 1470ea
    constructor() {
Packit 1470ea
        this.application = new Gtk.Application({
Packit 1470ea
            application_id: 'org.example.jstreeviewsimpleliststore'
Packit 1470ea
        });
Packit 1470ea
Packit 1470ea
        // Connect 'activate' and 'startup' signals to the callback functions
Packit 1470ea
        this.application.connect('activate', this._onActivate.bind(this));
Packit 1470ea
        this.application.connect('startup', this._onStartup.bind(this));
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'activate' signal presents window when active
Packit 1470ea
    _onActivate() {
Packit 1470ea
        this._window.present();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Callback function for 'startup' signal builds the UI
Packit 1470ea
    _onStartup() {
Packit 1470ea
        this._buildUI();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    // Build the application's UI
Packit 1470ea
    _buildUI() {
Packit 1470ea
        // Create the application window
Packit 1470ea
        this._window = new Gtk.ApplicationWindow({
Packit 1470ea
            application: this.application,
Packit 1470ea
            window_position: Gtk.WindowPosition.CENTER,
Packit 1470ea
            default_height: 250,
Packit 1470ea
            default_width: 100,
Packit 1470ea
            border_width: 20,
Packit 1470ea
            title: "My Phone Book"});
Packit 1470ea
Packit 1470ea
        // Create the underlying liststore for the phonebook
Packit 1470ea
        this._listStore = new Gtk.ListStore ();
Packit 1470ea
        this._listStore.set_column_types ([
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING,
Packit 1470ea
            GObject.TYPE_STRING]);
Packit 1470ea
Packit 1470ea
        // Data to go in the phonebook
Packit 1470ea
        let phonebook =
Packit 1470ea
            [{ name: "Jurg", surname: "Billeter", phone: "555-0123",
Packit 1470ea
                description: "A friendly person."},
Packit 1470ea
             { name: "Johannes", surname: "Schmid", phone: "555-1234",
Packit 1470ea
                description: "Easy phone number to remember."},
Packit 1470ea
             { name: "Julita", surname: "Inca", phone: "555-2345",
Packit 1470ea
                description: "Another friendly person."},
Packit 1470ea
             { name: "Javier", surname: "Jardon", phone: "555-3456",
Packit 1470ea
                description: "Bring fish for his penguins."},
Packit 1470ea
             { name: "Jason", surname: "Clinton", phone: "555-4567",
Packit 1470ea
                description: "His cake's not a lie."},
Packit 1470ea
             { name: "Random J.", surname: "Hacker", phone: "555-5678",
Packit 1470ea
                description: "Very random!"}];
Packit 1470ea
Packit 1470ea
        // Put the data in the phonebook
Packit 1470ea
        for (let i = 0; i < phonebook.length; i++ ) {
Packit 1470ea
            let contact = phonebook [i];
Packit 1470ea
            this._listStore.set (this._listStore.append(), [0, 1, 2, 3],
Packit 1470ea
                [contact.name, contact.surname, contact.phone, contact.description]);
Packit 1470ea
        }
Packit 1470ea
Packit 1470ea
        // Create the treeview
Packit 1470ea
        this._treeView = new Gtk.TreeView ({
Packit 1470ea
            expand: true,
Packit 1470ea
            model: this._listStore });
Packit 1470ea
Packit 1470ea
        // Create the columns for the address book
Packit 1470ea
        let firstName = new Gtk.TreeViewColumn ({ title: "First Name" });
Packit 1470ea
        let lastName = new Gtk.TreeViewColumn ({ title: "Last Name" });
Packit 1470ea
        let phone = new Gtk.TreeViewColumn ({ title: "Phone Number" });
Packit 1470ea
Packit 1470ea
        // Create a cell renderer for when bold text is needed
Packit 1470ea
        let bold = new Gtk.CellRendererText ({
Packit 1470ea
            weight: Pango.Weight.BOLD });
Packit 1470ea
Packit 1470ea
        // Create a cell renderer for normal text
Packit 1470ea
        let normal = new Gtk.CellRendererText ();
Packit 1470ea
Packit 1470ea
        // Pack the cell renderers into the columns
Packit 1470ea
        firstName.pack_start (bold, true);
Packit 1470ea
        lastName.pack_start (normal, true);
Packit 1470ea
        phone.pack_start (normal, true);
Packit 1470ea
Packit 1470ea
        // Set each column to pull text from the TreeView's model
Packit 1470ea
        firstName.add_attribute (bold, "text", 0);
Packit 1470ea
        lastName.add_attribute (normal, "text", 1);
Packit 1470ea
        phone.add_attribute (normal, "text", 2);
Packit 1470ea
Packit 1470ea
        // Insert the columns into the treeview
Packit 1470ea
        this._treeView.insert_column (firstName, 0);
Packit 1470ea
        this._treeView.insert_column (lastName, 1);
Packit 1470ea
        this._treeView.insert_column (phone, 2);
Packit 1470ea
Packit 1470ea
        // Create the label that shows details for the name you select
Packit 1470ea
        this._label = new Gtk.Label ({ label: "" });
Packit 1470ea
Packit 1470ea
        // Get which item is selected
Packit 1470ea
        this.selection = this._treeView.get_selection();
Packit 1470ea
Packit 1470ea
        // When something new is selected, call _on_changed
Packit 1470ea
        this.selection.connect ('changed', this._onSelectionChanged.bind(this));
Packit 1470ea
Packit 1470ea
        // Create a grid to organize everything in
Packit 1470ea
        this._grid = new Gtk.Grid;
Packit 1470ea
Packit 1470ea
        // Attach the treeview and label to the grid
Packit 1470ea
        this._grid.attach (this._treeView, 0, 0, 1, 1);
Packit 1470ea
        this._grid.attach (this._label, 0, 1, 1, 1);
Packit 1470ea
Packit 1470ea
        // Add the grid to the window
Packit 1470ea
        this._window.add (this._grid);
Packit 1470ea
Packit 1470ea
        // Show the window and all child widgets
Packit 1470ea
        this._window.show_all();
Packit 1470ea
    }
Packit 1470ea
Packit 1470ea
    _onSelectionChanged() {
Packit 1470ea
        // Grab a treeiter pointing to the current selection
Packit 1470ea
        let [ isSelected, model, iter ] = this.selection.get_selected();
Packit 1470ea
Packit 1470ea
        // Set the label to read off the values stored in the current selection
Packit 1470ea
        this._label.set_label ("\n" +
Packit 1470ea
            this._listStore.get_value (iter, 0) + " " +
Packit 1470ea
            this._listStore.get_value (iter, 1) + " " +
Packit 1470ea
            this._listStore.get_value (iter, 2) + "\n" +
Packit 1470ea
            this._listStore.get_value (iter, 3)
Packit 1470ea
        );
Packit 1470ea
    }
Packit 1470ea
};
Packit 1470ea
Packit 1470ea
// Run the application
Packit 1470ea
let app = new TreeViewExample ();
Packit 1470ea
app.application.run (ARGV);
Packit 1470ea
Packit 1470ea
  </section>
Packit 1470ea
Packit 1470ea
  <section id="in-depth">
Packit 1470ea
    <title>Documentación en profundidad</title>
Packit 1470ea

En este ejemplo se usa lo siguiente:

Packit 1470ea
<list>
Packit 1470ea
  <item>

<link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link>

</item>
Packit 1470ea
  <item>

<link href="http://developer.gnome.org/gtk3/stable/GtkApplicationWindow.html">Gtk.ApplicationWindow</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.CellRendererText.html">Gtk.CellRendererText</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.ListStore.html">Gtk.ListStore</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.TreeIter.html">Gtk.TreeIter</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.TreeSelection.html">Gtk.TreeSelection</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.TreeView.html">Gtk.TreeView</link>

</item>
Packit 1470ea
  <item>

<link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.TreeViewColumn.html">Gtk.TreeViewColumn</link>

</item>
Packit 1470ea
</list>
Packit 1470ea
  </section>
Packit 1470ea
</page>