Esta barra de estado registra cuántas veces se pulsó un botón. Las aplicaciones como gedit usan barras de estado para mostrar información a simple vista, y mostrar notificaciones sin interrumpir al usuario.
Los mensajes que se muestran en una barra de estado van a la parte superior de su pila, y pueden extraerse para mostrar el siguiente más reciente. También puede limpiar todos los mensajes de un tipo específico de una vez. Esta aplicación de ejemplo demuestra estas funciones.
#!/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.
const StatusbarExample = new Lang.Class({
Name: 'Statusbar Example',
// Create the application itself
_init: function() {
this.application = new Gtk.Application({
application_id: 'org.example.jsstatusbar',
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 «StatusBarExample». 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: 120,
default_width: 300,
title: "Button Clicker"});
// Create a paned interface
this._panes = new Gtk.Paned ({
orientation: Gtk.Orientation.VERTICAL });
La función «_buildUI» es donde se pone todo el código para crear la interfaz de usuario de la aplicación. El primer paso es crear una Gtk.ApplicationWindow nueva para poner dentro todos los widgets. El siguiente paso es crear una interfaz «Gtk.Paned» orientada verticalmente, para dividir la ventana en dos secciones. De esta manera la barra de estado se parece a aquellas usadas en otras aplicaciones, y permanece en la parte inferior de la ventana, incluso si el usuario la redimensiona.
// Create the statusbar
this._statusbar = new Gtk.Statusbar();
// Keep track of the number of times the button has been clicked
this.Clicks = 0;
this.ContextID = this._statusbar.get_context_id ("Number of Clicks");
// Give the statusbar an initial message
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
// Put the statusbar in its own frame at the bottom
this._barFrame = new Gtk.Frame ({
height_request: 30 });
this._barFrame.add (this._statusbar);
Aquí se crea la «Gtk.Statusbar», y se le empuja un mensaje para comenzar. Después se le da su propio cuadro estrecho en la parte inferior de la ventana.
Cada mensaje necesita tener un ID de contexto, que es un valor entero que puede obtener de la barra de estado con la función «get_context_id()». Su único parámetro es el valor de la cadena que usa para describir ese ID de contexto particular. Normalmente, obtendría un ID de contexto nuevo para distintos tipos de mensajes, para que pueda usar la función «remove()» para eliminar un mensaje específico y no sólo el más reciente de la pila. Sin embargo, este es un ejemplo simple con sólo un tipo de mensaje, por lo que sólo se usa uno para todo.
Se usa la función «push()» para empujar un mensaje nuevo a la pila. Su primer parámetro es el ID de contexto, y el segundo es el mensaje.
// Assemble the frames into the paned interface
this._panes.pack1 (this._topFrame, true, false);
this._panes.pack2 (this._barFrame, false, false);
// Put the panes into the window
this._window.add (this._panes);
// Show the window and all child widgets
this._window.show_all();
},
Este código termina de crear la ventana, empaquetando los marcos en el panel, añadiéndolo a la ventana, y diciéndole a la ventana que muestre todos los widgets hijos.
_clicked: function() {
// Increment the number of clicks by 1
this.Clicks++;
// Update the statusbar with the new number of clicks
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
},
_back: function () {
// If there have been any clicks, decrement by 1 and remove last statusbar update
if (this.Clicks > 0 ) {
this.Clicks--;
this._statusbar.pop (this.ContextID);
};
},
_clear: function () {
// Reset the number of clicks
this.Clicks = 0;
// Wipe out all the messages pushed to the statusbar
this._statusbar.remove_all (this.ContextID);
// Reset the statusbar's message
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
}
});
Aquí están funciones que muestran cómo empujar un mensaje a la pila, extraer el que está arriba de todo, y limpiar todos los mensajes de un ID de contexto particular. La función «pop()» sólo toma un parámetro, que es el ID de contexto para el tipo de mensaje del que quiere extraer el más reciente. La función «remove_all()» funciona de la misma manera, excepto que elimina todos los mensajes de ese tipo de la pila.
// Run the application
let app = new StatusbarExample ();
app.application.run (ARGV);
Finalmente, se crea una instancia nueva de la clase «StatusbarExample» terminada, y se ejecuta la aplicación.
#!/usr/bin/gjs
imports.gi.versions.Gtk = '3.0';
const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
class StatusbarExample {
// Create the application itself
constructor() {
this.application = new Gtk.Application({
application_id: 'org.example.jsstatusbar',
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: 120,
default_width: 300,
title: "Button Clicker"});
// Create a paned interface
this._panes = new Gtk.Paned ({
orientation: Gtk.Orientation.VERTICAL });
// Create the main button
this._clickMe = new Gtk.Button ({
label: "Click Me!" });
this._clickMe.connect ("clicked", this._clicked.bind(this));
// Create the back button
this._backButton = new Gtk.Button ({
label: "gtk-go-back",
use_stock: true });
this._backButton.connect ("clicked", this._back.bind(this));
// Create the clear button
this._clearButton = new Gtk.Button ({
label: "gtk-clear",
use_stock: true });
this._clearButton.connect ("clicked", this._clear.bind(this));
// Put the buttons in a grid
this._grid = new Gtk.Grid ({
halign: Gtk.Align.CENTER,
valign: Gtk.Align.CENTER });
this._grid.attach (this._backButton, 0, 0, 1, 1);
this._grid.attach_next_to (this._clickMe, this._backButton, Gtk.PositionType.RIGHT, 1, 1);
this._grid.attach_next_to (this._clearButton, this._clickMe, Gtk.PositionType.RIGHT, 1, 1);
// Put the grid in a large frame that fills most of the window
this._topFrame = new Gtk.Frame ({
border_width: 20,
height_request: 90,
width_request: 300});
this._topFrame.add (this._grid);
// Create the statusbar
this._statusbar = new Gtk.Statusbar();
// Keep track of the number of times the button has been clicked
this.Clicks = 0;
this.ContextID = this._statusbar.get_context_id ("Number of Clicks");
// Give the statusbar an initial message
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
// Put the statusbar in its own frame at the bottom
this._barFrame = new Gtk.Frame ({
height_request: 30 });
this._barFrame.add (this._statusbar);
// Assemble the frames into the paned interface
this._panes.pack1 (this._topFrame, true, false);
this._panes.pack2 (this._barFrame, false, false);
// Put the panes into the window
this._window.add (this._panes);
// Show the window and all child widgets
this._window.show_all();
}
_clicked() {
// Increment the number of clicks by 1
this.Clicks++;
// Update the statusbar with the new number of clicks
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
}
_back() {
// If there have been any clicks, decrement by 1 and remove last statusbar update
if (this.Clicks > 0 ) {
this.Clicks--;
this._statusbar.pop (this.ContextID);
};
}
_clear() {
// Reset the number of clicks
this.Clicks = 0;
// Wipe out all the messages pushed to the statusbar
this._statusbar.remove_all (this.ContextID);
// Reset the statusbar's message
this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks);
}
};
// Run the application
let app = new StatusbarExample ();
app.application.run (ARGV);
Gtk.Application
Gtk.ApplicationWindow
Gtk.Button
Gtk.Frame
Gtk.Paned
Gtk.Statusbar