GTK+ 2.0 Tree View Tutorial using Ocaml | ||
---|---|---|
Prev | Chapter 6. Selections, Double-Clicks and Context Menus | Next |
Context menus are context-dependent menus that pop up when a user right-clicks on a list or tree and usually let the user do something with the selected items or manipulate the list or tree in other ways.
Right-clicks on a tree view are caught just like mouse button clicks are caught with any other widgets, namely by connecting to the tree view's "button_press_event" signal handler (which is a GtkWidget signal, and as GtkTreeView is derived from GtkWidget it has this signal as well). Also, you should make sure that all functions provided in your context menu can also be accessed by other means such as the application's main menu. See the GNOME Human Interface Guidelines (HIG) for more details. Straight from the a-snippet-of-code-says-more-than-a-thousand-words-department, some code to look at:
(* file: popup.ml *) ... let cols = new GTree.column_list let col_name = cols#add Gobject.Data.string let col_age = cols#add Gobject.Data.int ... let on_doSomething treeview () = Printf.printf "Do something!\n"; flush stdout let view_popup_menu treeview ev = let menu = GMenu.menu () in let menuitem = GMenu.menu_item ~label:"Do something" ~packing:menu#append () in menuitem#connect#activate ~callback:(on_doSomething treeview); menu#popup ~button:(GdkEvent.Button.button ev) ~time:(GdkEvent.Button.time ev) let on_button_pressed treeview ev = if GdkEvent.Button.button ev = 3 then ( Printf.printf "Single right click on the tree view.\n"; (* optional: select row if no row is selected or only * one other row is selected (will only do something * if you set a tree selection mode as described later * in the tutorial) *) if true then begin let selection = treeview#selection in (* Note: gtk_tree_selection_count_selected_rows() does not * exist in gtk+-2.0, only in gtk+ >= v2.2 ! *) if selection#count_selected_rows <= 1 then ( let x = int_of_float (GdkEvent.Button.x ev) in let y = int_of_float (GdkEvent.Button.y ev) in let Some (path, _, _, _) = treeview#get_path_at_pos ~x ~y in selection#unselect_all (); selection#select_path path ) end; (* end of optional bit *) view_popup_menu treeview ev; true (* we handled this *) ) else false (* we did not handle this *) let create_view ~packing () = let view = GTree.view ~packing () in ... view#event#connect#button_press ~callback:(on_button_pressed view); ...