Creating custom stock items in GTK+

Tagged:  •    •    •  

Let's say you want to put a tool button with a custom image, which is not among the stock items, to the toolbar of your GTK+ application. Here is the code for creating additional stock items from custom images:

"Variously sized versions of an image is held inside an icon set and icon sets are held inside icon factories. You may put one size of an image inside an icon set and GTK+ will scale it appropriately for your usage."

"First create an icon factory."
myIconFactory := GtkIconFactory new.

"Add that factory as a default icon factory so that the icons inside it can be found by the application."
myIconFactory addDefault.

"The image we want to create the icon from."
myImage := GtkImage newFromFile: 'Path/To/My/Image.png'.

"Create an icon set with our image inside. Here we use the convenience method #newFromPixbuf to create an icon set with one image inside."
myIconSet := GtkIconSet newFromPixbuf: myImage getPixbuf.

"Finally, add our icon set to the icon factory and specify a stock item name for it. It is a convention to add a prefix for your application's custom stock item names."
myIconFactory add: 'myprefix-my-icon' iconSet: myIconSet.

Now you can use your new stock item like this:

GtkToolButton newFromStock: 'myprefix-my-icon'.

User login