开发者

Which is the best way to handle GtkMenu activate callback?

I have created a GtkMenu with 10 GtkMenuItems in it, and attached activate event to each menu item, but in callback function how should I get to know which menu item was actually selected?

I have added Call back to GtkMenuItem as follows:

   gtk_signal_connect_object( GTK_OBJECT(menu_items), "activate",
                              GTK_SIGNAL_FUNC(on_option_selected),
                              (gpointer)GINT_TO_POINTER( i ) );

and my call back function is as follows:

gboolean on_option_selected( GtkWidget *widget, gpointer user_data );

And tried to convert user_data as follows but getting garbage.

gint selected_index = GPOINTER_TO_INT( user_data );
开发者_StackOverflow社区

Thanks, PP


The easiest way is to use the gpointer user_data argument to the callback to encode this, somehow.

You might for instance pass an enum, using the GINT_TO_POINTER() and GPOINTER_TO_INT() macros to convert back and forth. The enum might be something like

enum { FILE_NEW, FILE_OPEN, FILE_SAVE, FILE_SAVEAS, FILE_QUIT };

or similar. The connect (assuming recent GTK+ 2.x) should look like this:

g_signal_connect(G_OBJECT(item_saveas), "activate", G_CALLBACK(on_option_selected), GINT_TO_POINTER(FILE_SAVEAS));

Or you can go all out and use GtkActions, but that might feel like a bit too much engineering, depends on the number of commands you need to work with.


Don't use gtk_signal_connect_object(), it's deprecated and replaced by g_signal_connect_swapped(). You get garbage, because with both of those functions, the instance and user_data are switched around. So you are actually converting the pointer to menu_items to an integer. Use g_signal_connect() like unwind says.

However, since you're probably just going to do a switch(selected_index) after that, I'd recommend writing one callback function for each menu item (e.g. on_new_selected(), on_open_selected(), on_save_selected(), etc.) and connecting each one separately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜