ComboBoxText (JavaScript) Taryn Fox jewelfox@fursona.net 2012 Un menú desplegable de solo texto Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 ComboBoxText

Un «ComboBox» es un menú desplegable. La diferencia entre un ComboBox y un «ComboBoxText» es que este sólo tiene opciones básicas de texto, mientras que un «ComboBox» completo usa un «ListStore» o «TreeStore» (que son básicamente hojas de cálculo) para mostrar cosas como opciones de bifurcación, o imágenes junto a cada opción.

A menos que necesite las características adicionales de un «ComboBox» completo, o si se siente cómodo trabajando con «ListStore» y «TreeStore», encontrará mucho más simple usar un «ComboBoxText» siempre que sea posible.

Bibliotecas que importar #!/usr/bin/gjs const Gtk = imports.gi.Gtk; const Lang = imports.lang;

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.

Crear la ventana de la aplicación const ComboBoxTextExample = new Lang.Class ({ Name: 'ComboBoxText Example', // Create the application itself _init: function () { this.application = new Gtk.Application ({ application_id: 'org.example.jscomboboxtext'}); // 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 windows 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 «MessageDialogExample». El código anterior crea una Gtk.Application para que vayan 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, title: "Welcome to GNOME", default_width: 200, border_width: 10 });

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.

Crear el ComboBoxText // Create the combobox this._comboBoxText = new Gtk.ComboBoxText(); // Populate the combobox let distros = ["Select distribution", "Fedora", "Mint", "Suse"]; for (let i = 0; i < distros.length; i++) this._comboBoxText.append_text (distros[i]); this._comboBoxText.set_active (0); // Connect the combobox's 'changed' signal to our callback function this._comboBoxText.connect ('changed', Lang.bind (this, this._onComboChanged));

Después de crear el «ComboBoxText», se usa su método append_text para añadirle cadenas de texto. Al igual que las entradas en una matriz, cada una tiene un número para identificarlas, comenzando por el 0. Para hacer las cosas más simples, puede crear una matriz para los datos del «ComboBoxText», y después usar un bucle «for» para añadirlos en orden, como aquí.

Después de poblar el «ComboBoxText», se activa su primera entrada, para ver la línea «Seleccionar distribución» antes de pulsarlo. Después se conecta su señal changed a la función «_onComboChanged», para que se llame siempre que haga una selección nueva del menú desplegable.

Si quiere añadirle una entrada a un «ComboBoxText», puede usar el método insert_text. Y si prefiere usar una cadena de texto como identificación de cada entrada en lugar de solo números, puede usar los métodos append e insert. Consulte los enlaces al final de este tutorial para ver detalles sobre su uso.

// Add the combobox to the window this._window.add (this._comboBoxText); // Show the window and all child widgets this._window.show_all(); },

Finalmente, se añade el «ComboBoxText» a la ventana, y se le dice que se muestre con su widget.

Función que maneja su selección _onComboChanged: function () { // The responses we'll use for our messagedialog let responses = ["", "Fedora is a community distro sponsored by Red Hat.", "Mint is a popular distro based on Ubuntu.", "SUSE is a name shared by two separate distros."];

Se va a crear un MessageDialog emergente, que muestre un mensaje a partir de qué distribución elija. Primero, se crea la matriz de respuestas para usar. Dado que la primera cadena del «ComboBoxText» es solo el mensaje «Seleccione distribución», la primera cadena de la matriz está vacía.

// Which combobox item is active? let activeItem = this._comboBoxText.get_active(); // No messagedialog if you chose "Select distribution" if (activeItem != 0) { this._popUp = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, buttons: Gtk.ButtonsType.OK, message_type: Gtk.MessageType.INFO, text: responses[activeItem]}); // Connect the OK button to a handler function this._popUp.connect ('response', Lang.bind (this, this._onDialogResponse)); // Show the messagedialog this._popUp.show(); } },

Antes de mostrar un «MessageDialog», se verifica que no ha elegido el mensaje «Seleccionar distribución». Después de eso, se establece su texto a la entrada en la matriz que le corresponde a la entrada activa en el «ComboBoxText». Esto se hace usando el método get_active, que devuelve la identificación numérica de su selección.

Otros métodos que puede usar incluyen get_active_id, que devuelve la identificación de texto que asignó append, y get_active_text, que devuelve el texto completo de la cadena que seleccionó.

Después de crear el «MessageDialog», se conecta su señal «response» a la función «onDialogResponse», y se le dice que se muestre.

_onDialogResponse: function () { this._popUp.destroy (); } });

Dado que el único botón que tiene el «MessageDialog» es un botón aceptar, no se necesita verificar su «response_id» para ver qué botón se pulsó. Todo lo que se hace aquí es destruir la ventana emergente.

// Run the application let app = new ComboBoxTextExample (); app.application.run (ARGV);

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

Código de ejemplo completo #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; class ComboBoxTextExample { // Create the application itself constructor() { this.application = new Gtk.Application ({ application_id: 'org.example.jscomboboxtext'}); // 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 windows 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, title: "Welcome to GNOME", default_width: 200, border_width: 10 }); // Create the combobox this._comboBoxText = new Gtk.ComboBoxText(); // Populate the combobox let distros = ["Select distribution", "Fedora", "Mint", "Suse"]; for (let i = 0; i < distros.length; i++) this._comboBoxText.append_text (distros[i]); this._comboBoxText.set_active (0); // Connect the combobox's 'changed' signal to our callback function this._comboBoxText.connect ('changed', this._onComboChanged.bind(this)); // Add the combobox to the window this._window.add (this._comboBoxText); // Show the window and all child widgets this._window.show_all(); } _onComboChanged() { // The responses we'll use for our messagedialog let responses = ["", "Fedora is a community distro sponsored by Red Hat.", "Mint is a popular distro based on Ubuntu.", "SUSE is a name shared by two separate distros."]; // Which combobox item is active? let activeItem = this._comboBoxText.get_active(); // No messagedialog if you chose "Select distribution" if (activeItem != 0) { this._popUp = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, buttons: Gtk.ButtonsType.OK, message_type: Gtk.MessageType.INFO, text: responses[activeItem]}); // Connect the OK button to a handler function this._popUp.connect ('response', this._onDialogResponse.bind(this)); // Show the messagedialog this._popUp.show(); } } _onDialogResponse() { this._popUp.destroy (); } }; // Run the application let app = new ComboBoxTextExample (); app.application.run (ARGV);
Documentación en profundidad

En este ejemplo se usa lo siguiente:

Gtk.Application

Gtk.ApplicationWindow

Gtk.ComboBoxText

Gtk.MessageDialog