# Toolbar created using Glade (Python)

Tiffany Antopolski
tiffany.antopolski@gmail.com 2012
Marta Maria Casetti
mmcasetti@gmail.com 2012
Sebastian Pölsterl
sebp@k-d-w.org 2011
Unha barra de botóns e outros widgets
Fran Dieguez
frandieguez@gnome.org 2012-2013.

# Barra de ferramentas creada empregando Glade

Este exemplo é similar a , agás que usa Glade para crear a barra de ferrametnas nun ficheiro .ui XML.

# Crear unha barra de ferramentas con Glade

To create the toolbar using the Glade Interface Designer:

Open Glade, and save the file as toolbar_builder.ui

Screenshot of Glade ui

Under Containers on the left hand side, right click on the toolbar icon and select Add widget as toplevel.

Screenshot of toolbar icon in Glade ui

Under the General tab on the bottom right, change the Name to toolbar and Show Arrow to No.

Screenshot of General tab

Under the Common tab, set Horizontal Expand to Yes.

Screenshot of Common tab

Prema co botón dereito sobre a barra de ferramentas na parte superior dereita e seleccione Editar. A xanela Editor da barra de ferramentas aparecerá.

Screenshot of where to right click to edit toolbar.

Queremos engadir 5 ToolButtons: Novo, Abrir, Desfacer, Pantalla completa e Saír da pantalla completa. Primeiro, precisamos engadir o ToolButton Novo.

Baixo a lapela Xerarquía, prema Engadir.

Cambie o nome do TollItem a new_button.

Scroll down and set Is important to Yes. This will cause the label of the ToolButton to be shown, when you view the toolbar.

Escriba o nome da acción: app.new.

Cambie a Etiqueta a Nova.

Seleccione o Id de inventario New desde o menú despregábel, ou o tipo gtk-new.

Repita os pasos de arriba cos TollButtons que faltan, coas seguintes propiedades:

Nome | É importante | Nome da acción | Etiqueta | ID de inventario
--- | --- | --- | --- | ---
open_button | Si | app.open | Open | gtk-open
undo_button | Si | win.undo | Desfacer | gtk-undo
fullscreen_button | Si | win.fullscreen | Pantalla completa | gtk-fullscreen
leave_fullscreen_button | Si | win.fullscreen | Saír do modo de pantalla completa | gtk-leave-fullscreen

Pechar o Editor de barra de ferramentas.

When our program will first start, we do not want the Leave Fullscreen ToolButton to be visible, since the application will not be in fullscreen mode. You can set this in the Common tab, by clicking the Visible property to No. The ToolButton will still appear in the interface designer, but will behave correctly when the file is loaded into your program code. Note that the method `show_all()` would override this setting - so in the code we have to use `show()` separately on all the elements.

Setting the visible property to No

Garde o seu traballo e saia de Glade.

The XML file created by Glade is shown below. This is the description of the toolbar. At the time of this writing, the option to add the class Gtk.STYLE_CLASS_PRIMARY_TOOLBAR in the Glade Interface did not exist. We can manually add this to the XML file. To do this, add the following XML code at line 9 of toolbar_builder.ui:

<style> <class name="primary-toolbar"/> </style>

Se non engade isto, o programa funcionará igual. Porén barra de ferramentas resultante semellará un pouco diferente á captura de pantalla da parte superior desta páxina.

<?xml version="1.0" encoding="UTF-8"?> <interface> <!-- interface-requires gtk+ 3.0 --> <object class="GtkToolbar" id="toolbar"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="hexpand">True</property> <property name="show_arrow">False</property> <child> <object class="GtkToolButton" id="new_button"> <property name="use_action_appearance">False</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="is_important">True</property> <property name="action_name">app.new</property> <property name="label" translatable="yes">New</property> <property name="use_underline">True</property> <property name="stock_id">gtk-new</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="open_button"> <property name="use_action_appearance">False</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="is_important">True</property> <property name="action_name">app.open</property> <property name="label" translatable="yes">Open</property> <property name="use_underline">True</property> <property name="stock_id">gtk-open</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="undo_button"> <property name="use_action_appearance">False</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="is_important">True</property> <property name="action_name">win.undo</property> <property name="label" translatable="yes">Undo</property> <property name="use_underline">True</property> <property name="stock_id">gtk-undo</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="fullscreen_button"> <property name="use_action_appearance">False</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="is_important">True</property> <property name="action_name">win.fullscreen</property> <property name="label" translatable="yes">Fullscreen</property> <property name="use_underline">True</property> <property name="stock_id">gtk-fullscreen</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="leave_fullscreen_button"> <property name="use_action_appearance">False</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="is_important">True</property> <property name="action_name">win.fullscreen</property> <property name="label" translatable="yes">Leave Fullscreen</property> <property name="use_underline">True</property> <property name="stock_id">gtk-leave-fullscreen</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> </object> </interface>

# Código usado para xerar este exemplo

Agora crearemos o código de embaixo, que engade a barra de ferrametnas desde o ficheiro que creamos.

from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Gio import sys

class MyWindow(Gtk.ApplicationWindow):

def __init__(self, app): Gtk.Window.__init__(self, title="Toolbar Example", application=app) self.set_default_size(400, 200)

# a grid to attach the toolbar (see below) grid = Gtk.Grid() self.add(grid) # we have to show the grid (and therefore the toolbar) with show(), # as show_all() would show also the buttons in the toolbar that we want to # be hidden (such as the leave_fullscreen button) grid.show()

# a builder to add the UI designed with Glade to the grid: builder = Gtk.Builder() # get the file (if it is there) try: builder.add_from_file("toolbar_builder.ui") except: print("file not found") sys.exit() # and attach it to the grid grid.attach(builder.get_object("toolbar"), 0, 0, 1, 1)

# two buttons that will be used later in a method self.fullscreen_button = builder.get_object("fullscreen_button") self.leave_fullscreen_button = builder.get_object( "leave_fullscreen_button")

# create the actions that control the window, connect their signal to a # callback method (see below), add the action to the window:

# undo undo_action = Gio.SimpleAction.new("undo", None) undo_action.connect("activate", self.undo_callback) self.add_action(undo_action)

# and fullscreen fullscreen_action = Gio.SimpleAction.new("fullscreen", None) fullscreen_action.connect("activate", self.fullscreen_callback) self.add_action(fullscreen_action)

# callback for undo def undo_callback(self, action, parameter): print("You clicked \"Undo\".")

# callback for fullscreen def fullscreen_callback(self, action, parameter): # check if the state is the same as Gdk.WindowState.FULLSCREEN, which # is a bit flag is_fullscreen = self.get_window().get_state( ) & Gdk.WindowState.FULLSCREEN != 0 if is_fullscreen: self.unfullscreen() self.leave_fullscreen_button.hide() self.fullscreen_button.show() else: self.fullscreen() self.fullscreen_button.hide() self.leave_fullscreen_button.show()

class MyApplication(Gtk.Application):

def __init__(self): Gtk.Application.__init__(self)

def do_activate(self): win = MyWindow(self) # show the window - with show() not show_all() because that would show also # the leave_fullscreen button win.show()

def do_startup(self): Gtk.Application.do_startup(self)

# actions that control the application: create, connect their signal to a # callback method (see below), add the action to the application

# new new_action = Gio.SimpleAction.new("new", None) new_action.connect("activate", self.new_callback) app.add_action(new_action)

# open open_action = Gio.SimpleAction.new("open", None) open_action.connect("activate", self.open_callback) app.add_action(open_action)

# callback for new def new_callback(self, action, parameter): print("You clicked \"New\".")

# callback for open def open_callback(self, action, parameter): print("You clicked \"Open\".")

app = MyApplication() exit_status = app.run(sys.argv) sys.exit(exit_status)

# Métodos útiles para Gtk.Builder

Para os métodos útiles para o widget Toolbar, vexa

Gtk.Builder constrúe unha interface desde unha definición de IU en XML.

`add_from_file(nomedeficheiro)` carga e analiza o ficheiro fornecido e combínao cos contidos actuais de Gtk.Builder.

`add_from_string(string)` parses the given string and merges it with the current contents of the Gtk.Builder.

`add_objects_from_file(filename, object_ids)` is the same as `add_from_file()`, but it loads only the objects with the ids given in the `object_id`s list.

`add_objects_from_string(string, object_ids)` is the same as `add_from_string()`, but it loads only the objects with the ids given in the `object_id`s list.

`get_object(object_id)` retrieves the widget with the id `object_id` from the loaded objects in the builder.

`get_objects()` devolve todos os obxectos cargados.

`connect_signals(handler_object)` connects the signals to the methods given in the `handler_object`. This can be any object which contains keys or attributes that are called like the signal handler names given in the interface description, e.g. a class or a dict. In line 39 the signal `"activate"` from the action `undo_action` is connected to the callback function `undo_callback()` using `action.connect(signal, callback function)`. See for a more detailed explanation.

# API References

Neste exemplo empregaremos o seguinte:

GtkGrid

GtkBuilder

GtkWidget

Event Structures