Google Ads

January 31, 2019

Create a stylish button in GTK+ (Custom widget creation)

Often times we want to create our own form of buttons and widgets when using widget libraries such as GTK+. Although, we could achieve this by creating theme files but sometimes it is just easier to implement such widget using drawing routines available. In this tutorial, I am going to show you how to create a stylish button in GTK+ by not using widget provided button but by using drawing routines available for GTK+ library like shown below:




First, we create four png images for the button for hover, normal, pressed states and mask. We are going to use Cairo library for drawing our button state images into its container. All the functions required for creating this button are part of Standard GTK+ 2 package, so no external dependencies! for the button creation.

Second, we load button png images using cairo_image_surface_create_from_png function.

Third, we prepare a mask for the button as the button can have any shape where some parts of the button are transparent. We create a pixmap as button mask using gdk_pixmap_new function and format the mask according to mask png file using Cairo drawing functions. Our style button contain would be a GTK+ drawing widget. Finally, we set the mask using gtk_widget_shape_combine_mask function.

Fourth, we have to be able to update the button look according to its state which is achieved by connecting different signals to button container and updating button state variable in the signals callback functions and finally drawing the button images using Cairo functions. The callbacks functions can also be used for achieving normal button operations.

That's it!

Watch the tutorial: