SirPL
SirPL

Reputation: 51

Button with image - images disappear

That's my very first post here. First of all I'd like to apologise for my poor english. I really hope you will understand what I try to say.

Ok, so there's my problem: I have a few buttons generated in loop:

int board = 4;
int board_2 = board*board;
GtkWidget *card_button[board_2];

char path[100];
sprintf(path,"res/0.png"); //path to default image
GtkWidget *button_image = gtk_image_new_from_file(path);

for(int i=0; i<board_2; i++)
{
    card_button[i] = gtk_button_new();
    gtk_button_set_image(card_button[i],button_image);
    gtk_grid_attach(GTK_GRID(grid),card_button[i],i%board,(i/board)+1,1,1);
    g_signal_connect(G_OBJECT(card_button[i]), "clicked", G_CALLBACK(game_engine), i);
}

game_engine function:

void game_engine(GtkWidget* widget, gpointer data)
{
    int button_id = (int)data;
    char path[30];
    sprintf(path,"res/%d.png",button_id);
    GtkWidget *button_image = gtk_image_new_from_file(path);
    gtk_button_set_image(widget, button_image);
}

When I click the button, everything seems to be ok (image shows on the button), but sometimes, besides showing image on clicked button, another image disappears. Moreover GTK shows following error on console:

(Program.exe:4920): Gtk-CRITICAL **: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed

I did some debbuging and found that this error is caused by gtk_button_set_image in game_engine function. I don't know what to do next. Thank you in advance for any help.

Upvotes: 1

Views: 1079

Answers (2)

SirPL
SirPL

Reputation: 51

I've found solution. To avoid losing images I had to use g_object_ref(button_image); So there's correct code:

void game_engine(GtkWidget* widget, gpointer data)
{        
    int button_id = (int)data;
    char path[30];
    sprintf(path,"res/%d.png",field[button_id].val);
    GtkWidget *button_image = gtk_image_new_from_file(path);
    g_object_ref(button_image);
    gtk_button_set_image(GTK_BUTTON(widget),button_image);
}

Upvotes: 2

ikstream
ikstream

Reputation: 448

So on your line

     gtk_button_set_image(widget, button_image);

you are using a GtkWidget* widget, but gtk_button_set_image expects:

    void gtk_button_set_image (GtkButton *button, GtkWidget *image);

so you could try to cast it (GtkButton should be below widget in hierachy)

    gtk_button_set_image((GtkButton *)widget, button_image);

or hand it over as a button instead of a GtkWidget. Your error message just tells you, that you are using the wrong type

Upvotes: 0

Related Questions