ToggleButton (JavaScript) Taryn Fox jewelfox@fursona.net 2012 Se mantiene presionado hasta que lo pulsa de nuevo Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 ToggleButton

Un «ToggleButton» es como un Button normal, excepto que se mantiene presionado cuando pulsa en él. Puede usarlo como un conmutador de encendido/apagado, para controlar cosas como el Spinner en este ejemplo.

El método «get_active» del ToggleButton devuelve «true» si está presionado, y «false» si no lo está. Su método «set_active» se usa si quiere cambiar su estado sin la necesidad de pulsarlo. Cuando cambia su estado de «pulsado» a «no pulsado» y viceversa, envía la señal «toggled», que puede conectar a una función para hacer algo.

Bibliotecas que importar #!/usr/bin/gjs const Gio = imports.gi.Gio; 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 ToggleButtonExample = new Lang.Class({ Name: 'ToggleButton Example', // Create the application itself _init: function() { this.application = new Gtk.Application({ application_id: 'org.example.jstogglebutton', flags: Gio.ApplicationFlags.FLAGS_NONE }); // 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 RadioButtonExample. 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, default_height: 300, default_width: 300, border_width: 30, title: "ToggleButton Example"});

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 «ToggleButton» y otros widgets // Create the spinner that the button stops and starts this._spinner = new Gtk.Spinner ({hexpand: true, vexpand: true});

Se quiere que este Spinner se expanda vertical y horizontalmente, para llenar tanto espacio como sea posible dentro de la ventana.

// Create the togglebutton that starts and stops the spinner this._toggleButton = new Gtk.ToggleButton ({label: "Start/Stop"}); this._toggleButton.connect ('toggled', Lang.bind (this, this._onToggle));

Crear un ToggleButton es muy similar a crear un Button normal. La mayor diferencia es que está manejando una señal «toggled» en lugar de una «clicked». Este código vincula la función _onToggle a esa señal, para que se llame cada vez que se conmute el ToggleButton.

// Create a grid and put everything in it this._grid = new Gtk.Grid ({ row_homogeneous: false, row_spacing: 15}); this._grid.attach (this._spinner, 0, 0, 1, 1); this._grid.attach (this._toggleButton, 0, 1, 1, 1);

Aquí se crea una Rejilla simple para organizar todo dentro, y después se le adjuntan el «Spinner» y el «ToggleButton».

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

Ahora se añade la rejilla a la ventana, y se le dice a esta que se muestre con sus widgets hijos cuando la aplicación arranque.

Hacer que algo suceda cuando se conmute el ToggleButton _onToggle: function() { // Start or stop the spinner if (this._toggleButton.get_active ()) this._spinner.start (); else this._spinner.stop (); } });

Cada vez que alguien conmuta el botón, esta función verifica cuál es su estado nuevo usando «get_active» e inicia o detiene el «spinner» consecuentemente. Se quiere que gire sólo cuando el botón está presionado, por lo que si «get_active» devuelve «true» se inicia el «spinner». De lo contrario, se le dice que se detenga.

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

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

Código de ejemplo completo #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; class ToggleButtonExample { // Create the application itself constructor() { this.application = new Gtk.Application({ application_id: 'org.example.jstogglebutton', flags: Gio.ApplicationFlags.FLAGS_NONE }); // 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: 300, default_width: 300, border_width: 30, title: "ToggleButton Example"}); // Create the spinner that the button stops and starts this._spinner = new Gtk.Spinner ({hexpand: true, vexpand: true}); // Create the togglebutton that starts and stops the spinner this._toggleButton = new Gtk.ToggleButton ({label: "Start/Stop"}); this._toggleButton.connect ('toggled', this._onToggle.bind(this)); // Create a grid and put everything in it this._grid = new Gtk.Grid ({ row_homogeneous: false, row_spacing: 15}); this._grid.attach (this._spinner, 0, 0, 1, 1); this._grid.attach (this._toggleButton, 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(); } _onToggle() { // Start or stop the spinner if (this._toggleButton.get_active ()) this._spinner.start (); else this._spinner.stop (); } }; // Run the application let app = new ToggleButtonExample (); app.application.run (ARGV);
Documentación en profundidad

Gtk.Application

Gtk.ApplicationWindow

Gtk.Grid

Gtk.Spinner

Gtk.ToggleButton