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 Etiqueta en la parte inferior de la ventana muestre más información acerca de cualquier nombre en el que pulse.
Un TreeView no es solamente un widget individual, sino que contiene varios más pequeños.
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.
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»).
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.
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.
#!/usr/bin/gjs
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const Pango = imports.gi.Pango;
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.
const TreeViewExample = new Lang.Class({
Name: 'TreeView Example with Simple ListStore',
// Create the application itself
_init: function() {
this.application = new Gtk.Application({
application_id: 'org.example.jstreeviewsimpleliststore'
});
// Connect 'activate' and 'startup' signals to the callback functions
this.application.connect('activate', Lang.bind(this, this._onActivate));
this.application.connect('startup', Lang.bind(this, this._onStartup));
},
// Callback function for 'activate' signal presents window when active
_onActivate: function() {
this._window.present();
},
// Callback function for 'startup' signal builds the UI
_onStartup: function() {
this._buildUI ();
},
Todo el código de este ejemplo va en la clase TreeViewExample. El código anterior crea una Gtk.Application en la que van los widgets y la ventana.
// Build the application's UI
_buildUI: function() {
// Create the application window
this._window = new Gtk.ApplicationWindow({
application: this.application,
window_position: Gtk.WindowPosition.CENTER,
default_height: 250,
default_width: 100,
border_width: 20,
title: "My Phone Book"});
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 Gtk.ApplicationWindow nueva para poner dentro todos los widgets.
// Create the underlying liststore for the phonebook
this._listStore = new Gtk.ListStore ();
this._listStore.set_column_types ([
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING]);
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).
Los tipos de datos GObject que puede usar incluyen:
En este caso, se está haciendo un ListStore de cuatro columnas, cada una conteniendo valores de cadenas.
Necesita poner la línea
// Data to go in the phonebook
this.phonebook =
let phonebook =
[{ name: "Jurg", surname: "Billeter", phone: "555-0123",
description: "A friendly person."},
{ name: "Johannes", surname: "Schmid", phone: "555-1234",
description: "Easy phone number to remember."},
{ name: "Julita", surname: "Inca", phone: "555-2345",
description: "Another friendly person."},
{ name: "Javier", surname: "Jardon", phone: "555-3456",
description: "Bring fish for his penguins."},
{ name: "Jason", surname: "Clinton", phone: "555-4567",
description: "His cake's not a lie."},
{ name: "Random J.", surname: "Hacker", phone: "555-5678",
description: "Very random!"}];
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.
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.
for (i = 0; i < phonebook.length; i++ ) {
let contact = phonebook [i];
this._listStore.set (this._listStore.append(), [0, 1, 2, 3],
[contact.name, contact.surname, contact.phone, contact.description]);
}
Este bucle
Un método
// Create the treeview
this._treeView = new Gtk.TreeView ({
expand: true,
model: this._listStore });
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.
// Create the columns for the address book
let firstName = new Gtk.TreeViewColumn ({ title: "First Name" });
let lastName = new Gtk.TreeViewColumn ({ title: "Last Name" });
let phone = new Gtk.TreeViewColumn ({ title: "Phone Number" });
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.
// Create a cell renderer for when bold text is needed
let bold = new Gtk.CellRendererText ({
weight: Pango.Weight.BOLD });
// Create a cell renderer for normal text
let normal = new Gtk.CellRendererText ();
// Pack the cell renderers into the columns
firstName.pack_start (bold, true);
lastName.pack_start (normal, true);
phone.pack_start (normal, true);
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
Aquí hay una lista de otras propiedades de texto que puede usar. Para usar estas constantes de Pango, asegúrese de poner la línea
firstName.add_attribute (bold, "text", 0);
lastName.add_attribute (normal, "text", 1);
phone.add_attribute (normal, "text", 2);
// Insert the columns into the treeview
this._treeView.insert_column (firstName, 0);
this._treeView.insert_column (lastName, 1);
this._treeView.insert_column (phone, 2);
Ahora que se han puesto los CellRenderer en las TreeViewColumn, se usa el método
El primer parámetro es qué CellRenderer se usará para procesar lo que se está obteniendo.
El segundo parámetro es qué tipo de información se obtendrá. En este caso, se le está haciendo saber que se procesa texto.
El tercer parámetro es de cuál de las columnas del ListStore se está obteniendo la información.
Después de haber preparado eso, se usa el método
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.
// Create the label that shows details for the name you select
this._label = new Gtk.Label ({ label: "" });
// Get which item is selected
this.selection = this._treeView.get_selection();
// When something new is selected, call _on_changed
this.selection.connect ('changed', Lang.bind (this, this._onSelectionChanged));
El método
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
// Create a grid to organize everything in
this._grid = new Gtk.Grid;
// Attach the treeview and label to the grid
this._grid.attach (this._treeView, 0, 0, 1, 1);
this._grid.attach (this._label, 0, 1, 1, 1);
// Add the grid to the window
this._window.add (this._grid);
// Show the window and all child widgets
this._window.show_all();
},
Después de haber terminado eso, se crea una Rejilla para poner todo dentro, se añade a la ventana y se le dice a esta que se muestre y revele su contenido.
_onSelectionChanged: function () {
// Grab a treeiter pointing to the current selection
let [ isSelected, model, iter ] = this.selection.get_selected();
// Set the label to read off the values stored in the current selection
this._label.set_label ("\n" +
this._listStore.get_value (iter, 0) + " " +
this._listStore.get_value (iter, 1) + " " +
this._listStore.get_value (iter, 2) + "\n" +
this._listStore.get_value (iter, 3));
}
});
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
Después de haber hecho eso, se llama a la función
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.
// Run the application
let app = new TreeViewExample ();
app.application.run (ARGV);
Finalmente, se crea una instancia nueva de la clase TreeViewExample terminada, y se ejecuta la aplicación.
#!/usr/bin/gjs
imports.gi.versions.Gtk = '3.0';
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Pango = imports.gi.Pango;
class TreeViewExample {
// Create the application itself
constructor() {
this.application = new Gtk.Application({
application_id: 'org.example.jstreeviewsimpleliststore'
});
// Connect 'activate' and 'startup' signals to the callback functions
this.application.connect('activate', this._onActivate.bind(this));
this.application.connect('startup', this._onStartup.bind(this));
}
// Callback function for 'activate' signal presents window when active
_onActivate() {
this._window.present();
}
// Callback function for 'startup' signal builds the UI
_onStartup() {
this._buildUI();
}
// Build the application's UI
_buildUI() {
// Create the application window
this._window = new Gtk.ApplicationWindow({
application: this.application,
window_position: Gtk.WindowPosition.CENTER,
default_height: 250,
default_width: 100,
border_width: 20,
title: "My Phone Book"});
// Create the underlying liststore for the phonebook
this._listStore = new Gtk.ListStore ();
this._listStore.set_column_types ([
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING]);
// Data to go in the phonebook
let phonebook =
[{ name: "Jurg", surname: "Billeter", phone: "555-0123",
description: "A friendly person."},
{ name: "Johannes", surname: "Schmid", phone: "555-1234",
description: "Easy phone number to remember."},
{ name: "Julita", surname: "Inca", phone: "555-2345",
description: "Another friendly person."},
{ name: "Javier", surname: "Jardon", phone: "555-3456",
description: "Bring fish for his penguins."},
{ name: "Jason", surname: "Clinton", phone: "555-4567",
description: "His cake's not a lie."},
{ name: "Random J.", surname: "Hacker", phone: "555-5678",
description: "Very random!"}];
// Put the data in the phonebook
for (let i = 0; i < phonebook.length; i++ ) {
let contact = phonebook [i];
this._listStore.set (this._listStore.append(), [0, 1, 2, 3],
[contact.name, contact.surname, contact.phone, contact.description]);
}
// Create the treeview
this._treeView = new Gtk.TreeView ({
expand: true,
model: this._listStore });
// Create the columns for the address book
let firstName = new Gtk.TreeViewColumn ({ title: "First Name" });
let lastName = new Gtk.TreeViewColumn ({ title: "Last Name" });
let phone = new Gtk.TreeViewColumn ({ title: "Phone Number" });
// Create a cell renderer for when bold text is needed
let bold = new Gtk.CellRendererText ({
weight: Pango.Weight.BOLD });
// Create a cell renderer for normal text
let normal = new Gtk.CellRendererText ();
// Pack the cell renderers into the columns
firstName.pack_start (bold, true);
lastName.pack_start (normal, true);
phone.pack_start (normal, true);
// Set each column to pull text from the TreeView's model
firstName.add_attribute (bold, "text", 0);
lastName.add_attribute (normal, "text", 1);
phone.add_attribute (normal, "text", 2);
// Insert the columns into the treeview
this._treeView.insert_column (firstName, 0);
this._treeView.insert_column (lastName, 1);
this._treeView.insert_column (phone, 2);
// Create the label that shows details for the name you select
this._label = new Gtk.Label ({ label: "" });
// Get which item is selected
this.selection = this._treeView.get_selection();
// When something new is selected, call _on_changed
this.selection.connect ('changed', this._onSelectionChanged.bind(this));
// Create a grid to organize everything in
this._grid = new Gtk.Grid;
// Attach the treeview and label to the grid
this._grid.attach (this._treeView, 0, 0, 1, 1);
this._grid.attach (this._label, 0, 1, 1, 1);
// Add the grid to the window
this._window.add (this._grid);
// Show the window and all child widgets
this._window.show_all();
}
_onSelectionChanged() {
// Grab a treeiter pointing to the current selection
let [ isSelected, model, iter ] = this.selection.get_selected();
// Set the label to read off the values stored in the current selection
this._label.set_label ("\n" +
this._listStore.get_value (iter, 0) + " " +
this._listStore.get_value (iter, 1) + " " +
this._listStore.get_value (iter, 2) + "\n" +
this._listStore.get_value (iter, 3)
);
}
};
// Run the application
let app = new TreeViewExample ();
app.application.run (ARGV);
En este ejemplo se usa lo siguiente:
Gtk.Application
Gtk.ApplicationWindow
Gtk.CellRendererText
Gtk.ListStore
Gtk.TreeIter
Gtk.TreeSelection
Gtk.TreeView
Gtk.TreeViewColumn