Search code examples
pythongtkgtk4

How to attach a gtk4 PopoverMenu to a parent widget?


This should be a no-brainer but I just can't seem to figure it out. If I build a Gtk.PopoverMenu:

menu = Gio.Menu.new()
test = Gio.MenuItem.new(label='test', detailed_action='win.test')
menu.append_item(test)
popup = Gtk.PopoverMenu.new_from_model(menu)

I don't know how to attach it to the parent widget (in my case a ListBox item). The API docs say "Popovers are attached to a parent widget" but there seems to be no relevant method for attaching it to the parent. Trying to popup.popup() results in a warning "Calling gtk_widget_realize() on a widget that isn't inside a toplevel window is not going to work very well. Widgets must be inside a toplevel container before realizing them", and a subsequent segfault.


Solution

  • To set the parent of the PopoverMenu, just use its set_parent() method to set the parent to any widget:

    ...
    popup = Gtk.PopoverMenu.new_from_model(menu)
    popup.set_parent(parent_widget)