How do I do something when user right click in a treeview's row?
Asked
Active
Viewed 3,440 times
5
-
2Please post your solution as an answer on here and accept it. – CodeMouse92 Sep 12 '11 at 19:02
1 Answers
3
It's really easy, just listen to the "button-press-event" signal and use treeview.get_path_at_pos()
to figure the selected row:
def button_press_event(treeview, event):
if event.button == 3: # right click
model, path = treeview.get_path_at_pos(int(event.x), int(event.y))
# do something with the selected path
treeview.connect('button-press-event' , button_press_event)

gpoo
- 8,408
- 3
- 38
- 53

Johan Dahlin
- 25,300
- 6
- 40
- 55
-
See also: [Chapter 16: Menus](http://python-gtk-3-tutorial.readthedocs.org/en/latest/menus.html) from the Python Gtk+ 3.0 tutorial. – f4lco Jan 25 '13 at 16:36
-
1Maybe it's GTK2 vs GTK3, but according to [pygtk 2 doc](http://www.pygtk.org/pygtk2reference/class-gtktreeview.html#method-gtktreeview--get-path-at-pos) it should be something like `path, column, __, __ = treeview.get_path_at_pos(int(event.x), int(event.y))` – Zvika Oct 07 '14 at 05:58
-
1Watch out: you don't necessarily want "button-press-event" unless your aim is to show a popup menu. If for instance you want to just execute some action on the clicked row, you will want "button-release-event". This will guarantee that when you right click on a new row, it gets selected (default handler for "button-press-event") before anything else happens. – Pietro Battiston Dec 01 '14 at 16:39
-
@PietroBattiston you can return True/False to control whether that kind of event propagation should happen or not. – Johan Dahlin Dec 03 '14 at 17:18
-
Yes, but order can matter: you probably want to first have the line selected, then execute your callback with the updated selection. (plus: in general - popups are an exception - whenever you say "click" you mean "button release") – Pietro Battiston Dec 03 '14 at 17:50
-
@PietroBattiston Yes, popups should generally be release, but for other actions that you want to happen later, you can use gobject.idle_add(), not pretty but it works. – Johan Dahlin Dec 04 '14 at 14:27
-
@JohanDahlin no, I think popups should be "press", and precisely in this sense they are an exception. Yes, you'll probably get the same result with glib.idle_add() , it's just more complicated and I fail to see any benefit. – Pietro Battiston Dec 05 '14 at 10:10