29 Mart 2014 Cumartesi

How to use Gtk+3 Popovers with Python

Popovers are great. If you do not know what they are yet, have a look here, or here. They are like right click menus, but way more functional.

However, there is yet so little documentation, and only an example in C by gtk3-demo, so I have needed some time to get it working on Python, and this is why I am posting about this.

from gi.repository import Gtk

def on_click(button):
    if popover.get_visible():

#Creating the window
window = Gtk.Window(title="Hello Popover")
window.connect("destroy", lambda w: Gtk.main_quit())

#Creating and placing a button.
box = Gtk.Box(spacing = 60)
button = Gtk.Button("Toggle popover")
button.connect("clicked", on_click)

#Creating a popover
popover = Gtk.Popover.new(button)
label = Gtk.Label("Hi!")



So, here is what I have been missing.
Firstly, popover = Gtk.Popover(); popover.set_parent(button) does not work.
Secondly, popover does not show up, if there is not enough space in window (it actually does, but is not visible). This is why the button is wrapped in a box in this example.
Lastly, if the content is smaller than the arrow, so will the popover be, which looks ugly, so you may want to set a size request if there is only one label in the popover. However, I can not think of any practical reason to create a popover with a single label in it.

Happy hacking!