Hello.
I’m writing a program that incorporates play/pause button. So when a user clicks on the button its icon should change. I have decided that the best way to do this would be to create these icons and keep pointers to them and later just add them to the button using gtk_button_set_image
.
Adding them for the first time to the button works (play icon when the program starts and pause icon when the button is pressed for the first time) but it doesn’t work for consequent additions.
I wrote a small program to show you what I mean.
#include <gtk/gtk.h>
struct Icons
{
GtkWidget *play;
GtkWidget *pause;
};
static void button_clicked(GtkWidget *button, struct Icons *icons)
{
static gboolean play = TRUE;
play = !play;
if (play)
gtk_button_set_image(GTK_BUTTON(button), icons->play);
else
gtk_button_set_image(GTK_BUTTON(button), icons->pause);
}
int main()
{
gtk_init(NULL, NULL);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 300, 300);
GtkWidget *button = gtk_button_new();
struct Icons icons;
icons.play = gtk_image_new_from_icon_name("media-playback-start", GTK_ICON_SIZE_BUTTON);
icons.pause = gtk_image_new_from_icon_name("media-playback-pause", GTK_ICON_SIZE_BUTTON);
gtk_button_set_image(GTK_BUTTON(button), icons.play);
gtk_container_add(GTK_CONTAINER(window), button);
g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect(button, "clicked", G_CALLBACK(button_clicked), &icons);
gtk_widget_show_all(window);
gtk_main();
}
Try clicking on the button more than once and you’ll see what I mean.
Why is this happening and how can I fix it? I have already found a solution, creating new icon every time the button is clicked, but that is very inefficient compared to what i had in mind when I encountered this problem so I hope I won’t have to use that.