Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the deprecated gtk3 GtkImageMenuItem

The official GTK3 documentation for replacement is a bad joke:

Use gtk_menu_item_new() instead.

After some research it almost feels like the GTK team wants to punish GTK package users. Of course, gtk_menu_item has no native support for images. I found this piece of code which seems to be the recommend approach but it produces menu items with ugly left padding:

ugly left padding

First item on the picture uses the recommended replacement. All other items use the deprecated GtkImageMenuItem. Here the related code creating the first item:

mi = gtk_menu_item_new();
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
icon = gtk_image_new_from_icon_name ("document-open", GTK_ICON_SIZE_MENU);
label = gtk_label_new (_("Open"));
gtk_container_add (GTK_CONTAINER (box), icon);
gtk_container_add (GTK_CONTAINER (box), label);
gtk_container_add (GTK_CONTAINER (mi), box);
gtk_widget_show_all(mi);
gtk_widget_set_sensitive(mi, TRUE);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi);

I have no idea how to get rid of that ugly left-padding. If the padding would vanish, I could go for this approach.

Another option to replace GtkImageMenuItem seems to be to write a own subclass of GtkMenuItem. Which would be a lot of work. Maybe there are some implementations around?

Yet another option seems to be the usage of GMenu instead of GtkMenu. GMenu provides g_menu_item_set_icon. However, replacing the whole menu is a drastic step (and I did not check so far how it would look like).

By the way: why exactly are there two different menu approaches in Glib/GTK which are not compatible with each other?

Any hints on which would be the best way to go for me ?

like image 639
Alex Avatar asked Oct 26 '25 06:10

Alex


1 Answers

GTK just doesn't intend to support image menu items going forward. (They're considered bad practice in modern UI by some.) However, you don't have to replace it just because it's deprecated; it will continue to work in GTK 3.x. If you wanted to continue to use it in GTK 4 and beyond you could create your own subclass but the path of least resistance is probably to just go with the flow and avoid mixing images in the menus.

As for the screenshot above I would expect that the left padding might disappear if you removed the other image menu items and replaced them with your replacement code. In that case you could put extra left padding on the menu items where you didn't add images, using CSS.

like image 81
ptomato Avatar answered Oct 28 '25 21:10

ptomato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!