Application

An Application class handles various common functions for creating a program, such as integration with the desktop, session management and initialisation.

Constructor

The Application can be constructed using the following:

application = Gtk.Application()

Methods

A Window can be added to and removed from an Application via:

application.add_window(window)
application.remove_window(window)

To retrieve a list of Window’s attached to an application call:

application.get_windows()

The active window can be found using:

application.get_active_window()

A menubar can be defined for the Application after it has been initialised:

application.set_menubar(menubar)

The menubar object needs to be a MenuModel object.

Another type of menu is the App Menu, which contains some common functions such as Quit or Preferences. This can be added using:

application.set_app_menu(menu)

Again, the menu object specified should be a MenuModel.

Signals

The commonly used signals of an Application are:

"window-added" (application, window)
"window-removed" (application, window)

The "window-added" and "window-removed" signals emit from the Application when the .add_window() and .remove_window() methods are called.

Example

Below is an example of a Application:

#!/usr/bin/env python3

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

class ApplicationWindow(Gtk.ApplicationWindow):
    def __init__(self, application):
        Gtk.Window.__init__(self, application=application)
        self.set_title("Application")
        self.set_default_size(200, 200)

        grid = Gtk.Grid()
        self.add(grid)

        menubutton = Gtk.MenuButton()
        grid.attach(menubutton, 0, 0, 1, 1)

        menumodel = Gio.Menu()
        menubutton.set_menu_model(menumodel)
        menumodel.append("New", "app.new")
        menumodel.append("Quit", "app.quit")

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

    def do_activate(self):
        window = ApplicationWindow(self)
        window.show_all()

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

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

        quit_action = Gio.SimpleAction.new("quit", None)
        quit_action.connect("activate", self.quit_callback)
        self.add_action(quit_action)

    def new_callback(self, action, parameter):
        print("You clicked New")

    def quit_callback(self, action, parameter):
        print("You clicked Quit")
        self.quit()

application = Application()
exit_status = application.run(sys.argv)
sys.exit(exit_status)

Download: Application