How to get item under GTK 4 ListView

Hi! I am trying to select ListView items on right-click and display a context menu using Python, but I can’t seem to find anything in the API or elsewhere online describing how I can convert a cursor’s position on a screen to the corresponding ListViewItem. Is there a way to do this?

That’s not really how you want to add a popup menu to a list view item: it’s how you would do it for a GtkTreeView because cell renderers are not widgets and cannot receive events. Items in a list view are widgets, so if you want to add a menu you should set it up when you create the item widget in your factory.

1 Like

Ok… That would do it, thanks!

Would you happen to know of any good examples of this?

When you create the widget that will represent the item in the ListView you have to add the menu (I will consider that you already have a class ready with the menu).

my_widget.menu = MyMenu()
my_widget.menu.set_parent(my_widget)

a Gtk.GestureClick to capture the click.

click = Gtk.GestureClick.new()
click.set_button(3)
click.connect("released", on_right_click)

my_widget.add_controller(click)

and the function to open the menu.


on_right_click(event: Gtk.GestureClick,
                         n_pres: int,
                         x: int,
                         y:int)

  my_widget._menu.set_offset(x, y)
  my_widget._menu.set_pointing_to(Gdk.Rectangle(x, y, 1, 1))
  my_widget._menu.popup()
2 Likes

Works like a charm… thanks :slight_smile:

1 Like

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