Debian Codegraph @

docs/tutorials/gtk4/examples/popover_menu.py

raw
1 import gi
2
3 gi.require_version("Gtk", "4.0")
4 from gi.repository import Gio, Gtk
5
6 # This would typically be its own file
7 MENU_XML = """
8 <?xml version='1.0' encoding='UTF-8'?>
9 <interface>
10 <menu id='app-menu'>
11 <section>
12 <item>
13 <attribute name='label'>About</attribute>
14 <attribute name='action'>app.about</attribute>
15 </item>
16 <item>
17 <attribute name='label'>Quit</attribute>
18 <attribute name='action'>app.quit</attribute>
19 </item>
20 </section>
21 </menu>
22 </interface>
23 """
24
25
26 class AppWindow(Gtk.ApplicationWindow):
27 def __init__(self, **kwargs):
28 super().__init__(**kwargs)
29
30 self.set_default_size(300, 200)
31
32 headerbar = Gtk.HeaderBar()
33 self.set_titlebar(headerbar)
34
35 builder = Gtk.Builder.new_from_string(MENU_XML, -1)
36 menu_model = builder.get_object("app-menu")
37
38 button = Gtk.MenuButton(menu_model=menu_model)
39 headerbar.pack_end(button)
40
41
42 class Application(Gtk.Application):
43 def __init__(self, **kwargs):
44 super().__init__(application_id="com.example.App", **kwargs)
45 self.window = None
46
47 def do_startup(self):
48 Gtk.Application.do_startup(self)
49
50 action = Gio.SimpleAction(name="about")
51 action.connect("activate", self.on_about)
52 self.add_action(action)
53
54 action = Gio.SimpleAction(name="quit")
55 action.connect("activate", self.on_quit)
56 self.add_action(action)
57
58 def do_activate(self):
59 # We only allow a single window and raise any existing ones
60 if not self.window:
61 # Windows are associated with the application
62 # when the last one is closed the application shuts down
63 self.window = AppWindow(application=self, title="Main Window")
64
65 self.window.present()
66
67 def on_about(self, action, param):
68 about_dialog = Gtk.AboutDialog(transient_for=self.window, modal=True)
69 about_dialog.present()
70
71 def on_quit(self, action, param):
72 self.quit()
73
74
75 app = Application()
76 app.run(None)