Re: [gtk-list] Help with popup menus



>  Has anyone got a simple piece of code which produces
>  popup (context-sensitive) menus?

Sure.  Try the following short program.

Umm, maybe this could go in the FAQ or tutorial or something?  It
sounds to me like a useful code snippet to have around.

----------------------------------------------------------------------
#include <gtk/gtk.h>

static void
print_item (GtkWidget *widget, gpointer data)
{
	printf ("%s\n", (char *) data);
}

static GtkWidget *
build_menu (void)
{
	static char *items[] = {
		"Hello world",
		"Foo bar",
		"Fee fi fo fum"
	};
	GtkWidget *menu;
	GtkWidget *item;
	int i;

	menu = gtk_menu_new ();

	for (i = 0; i < (sizeof (items) / sizeof (items[0])); i++) {
		item = gtk_menu_item_new_with_label (items[i]);
		gtk_signal_connect (GTK_OBJECT (item), "activate",
				    (GtkSignalFunc) print_item,
				    items[i]);
		gtk_widget_show (item);
		gtk_menu_append (GTK_MENU (menu), item);
	}

	return menu;
}

static gint
do_popup (GtkWidget *widget, GdkEventButton *event, gpointer data)
{
	static GtkWidget *menu;

	if (!menu)
		menu = build_menu ();

	gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL, 
			event->button, event->time);

	return FALSE;
}

int
main (int argc, char **argv)
{
	GtkWidget *window;
	GtkWidget *label;

	gtk_init (&argc, &argv);

	window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_widget_set_events (window,
			       (gtk_widget_get_events (window)
				| GDK_BUTTON_PRESS_MASK
				| GDK_BUTTON_RELEASE_MASK));

	gtk_signal_connect (GTK_OBJECT (window), "button_press_event",
			    (GtkSignalFunc) do_popup,
			    NULL);

	label = gtk_label_new ("Click me");
	gtk_container_add (GTK_CONTAINER (window), label);
	gtk_widget_show (label);

	gtk_widget_show (window);
	gtk_main ();
	return 0;
}
----------------------------------------------------------------------

Good luck,

  Quartic



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]