Popover doesn't popup as expected

Hi. I have two popovers p1 and p2. p1 should pop up when you left click a button (Gtk.Button) and p2 should pop up when you right click the button. p2 works as expected but not p1. But if I replace the button with a Gtk.MenuButton it works fine. Please help me in troubleshooting this issue.

Source
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

grid = Gtk.Grid()
but = Gtk.Button(label="Click")
label = Gtk.Label(label='''
This is just a placeholder text,
You click the button above me,
This does not bring the popover at best,
With the left mouse button as you see.

The right mouse button works as fine,
it makes the popover just shine,
my mouse is all working good,
then what makes the program look rude?
''')

grid.attach(but, 0, 0, 1, 1)
grid.attach(label, 0, 1, 1, 1)

p1 = Gtk.Popover()

l1 = Gtk.Label(label='''
My name is popover 1,
working with Gtk is all fun,
just some random bugs thrown at you,
but it can be solved, thats damn true.''')

p1.add(l1)
p1.set_relative_to(but)

p2 = Gtk.Popover()

l2 = Gtk.Label(label='''
My name is popover 2,
Don't call me with name 'foo',
I always love to popup,
with your permission to keep up.''')

p2.add(l2)
p2.set_relative_to(but)

l1.show_all()
l2.show_all()

def click(but, event):
    if event.type == 4:
        if event.button.button == 1:
            print("Left Mouse Button (1) clicked")
            p1.popup()
        elif event.button.button == 3:
            print("Right Mouse Button (2) clicked")
            p2.popup()

but.connect("event", click)
win = Gtk.Window()
win.connect("destroy", Gtk.main_quit)
win.add(grid)
win.show_all()
Gtk.main()

Can you describe how is not working as expected? maybe provide a minimal example?

I provided the sourcecode itself. And as described in my question itself, if I left click (using mouse) on the button, the popover doesn’t popup

I see, the problem is that:

  1. you click on the button.
  2. the popover is set to show.
  3. but because the button grabs focus, the popover hides again.

All too quickly so you don’t notice.

but.set_can_focus(False)

Will fix that.

It is more conventional to use button-press-event instead of event. (You could have used event.type == Gdk.EventType.BUTTON_PRESS anyway).

If you return Gdk.EVENT_STOP (aka True) from your event handler, the button won’t receive the event, but that means it won’t respond visually either.

A better option would be to popup on release by connecting to the button’s clicked signal and using a Gtk.GestureMultiPress for right click (or button-release-event for the legacy method).

1 Like

Excellent. Thanks a lot for explaining the mechanism too, thank you

Thanks, surely will take your points into consideration.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.