There is no full documentation about how to use Gtk.Builder
in PyGObject
to create a menubar.
I don't use that Gtk.UIManager
because it is deprecated.
The example code below is based on my experience with Gtk.UIManager
.
In the example should appear a menubar with Foo as a top menu group having an clickable item Bar.
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gio
class Window(Gtk.ApplicationWindow):
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(200, 100)
#
self.interface_info = """
<interface>
<menu id='TheMenu'>
<section>
<attribute name='foo'>Foo</attribute>
<item>
<attribute name='bar'>Bar</attribute>
</item>
</section>
</menu>
</interface>
"""
builder = Gtk.Builder.new_from_string(self.interface_info, -1)
action_bar = Gio.SimpleAction.new('bar', None)
action_bar.connect('activate', self.on_menu)
self.add_action(action_bar)
menubar = builder.get_object('TheMenu')
# layout
self.layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.layout.pack_start(menubar, True, True, 0)
self.add(self.layout)
self.connect('destroy', Gtk.main_quit)
self.show_all()
def on_menu(self, widget):
print(widget)
if __name__ == '__main__':
win = Window()
Gtk.main()
The current error is
Traceback (most recent call last):
File "./_menubar.py", line 46, in <module>
win = Window()
File "./_menubar.py", line 36, in __init__
self.layout.pack_start(menubar, True, True, 0)
TypeError: argument child: Expected Gtk.Widget, but got gi.repository.Gio.Menu
I am unsure about
- How to create the XML string.
- How to get the menubar-widget.
- How to create Actions/Click-handlers for menu items.
Of course the question could be extended to toolbars but I wouldn't made it to complexe.
btw: I don't want to use Gtk.Application.set_menubar()
. Because there is no Gtk.Application.set_toolbar()
and currently I see no advantage on having a Gtk-based application object.
EDIT: I also tried this variant (without any success):
gio_menu = builder.get_object('TheMenu')
menubar = Gtk.Menubar.new_from_model(gio_menu)