Search code examples
cgtk2

Redefine a label after a click button in GTK+2


I had the following code and I want to change the value of the label "title" when I press te button "hlpBtn" but I have troubles with it.

#include <gtk/gtk.h>

void button_clicked(GtkWidget *widget, gpointer data)
{
    GtkWidget *title = (GtkWidget *) data;
    title = gtk_label_new("DECODED!!");
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *table;
  GtkWidget *title;
  GtkWidget *wins;
  GtkWidget *halign;
  GtkWidget *halign2;
  GtkWidget *hlpBtn;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_widget_set_size_request (window, 650, 850);

  gtk_window_set_title(GTK_WINDOW(window), "Windows");

  gtk_container_set_border_width(GTK_CONTAINER(window), 15);

  table = gtk_table_new(6, 4, FALSE);
  gtk_table_set_col_spacings(GTK_TABLE(table), 3);
  gtk_table_set_row_spacing(GTK_TABLE(table), 0, 3);

  title = gtk_label_new("Decrypting code...");
  halign = gtk_alignment_new(0, 0, 0, 0);
  gtk_container_add(GTK_CONTAINER(halign), title);
  gtk_table_attach(GTK_TABLE(table), halign, 0, 1, 0, 1,
  GTK_FILL, GTK_FILL, 0, 0);

 halign2 = gtk_alignment_new(0, 1, 0, 0);
  hlpBtn = gtk_button_new_with_label("RUN");
  gtk_container_add(GTK_CONTAINER(halign2), hlpBtn);
  gtk_widget_set_size_request(hlpBtn, 70, 30);
  gtk_table_set_row_spacing(GTK_TABLE(table), 3, 5);
  gtk_table_attach(GTK_TABLE(table), halign2, 0, 1, 4, 5,
      GTK_FILL, GTK_FILL, 0, 0);

   g_signal_connect(G_OBJECT(hlpBtn), "clicked",
      G_CALLBACK(button_clicked), title);
gtk_container_add(GTK_CONTAINER(window), table);

  g_signal_connect(G_OBJECT(window), "destroy",
        G_CALLBACK(gtk_main_quit), G_OBJECT(window));

  gtk_widget_show_all(window);
  gtk_main();

  return 0;
}

My intention is to call the funcition button_clicked when I press hlpBtn and then changue title from "Decrypting code..." to "DECODED!!".

What is wrong here?

Thank you.


Solution

  • Why don't you do something like this, instead of creating a new label?

    void button_clicked(GtkWidget *widget, gpointer data)
    {
        gtk_label_set_text((GtkLabel *)data, "DECODED!!");
    }
    

    What's wrong with your code: you take a pointer to an existing label, make a local copy of it, create a new label and overwrite the local pointer with the pointer to the new item. The problem is, overwriting the pointer does by no mean replace the original item within the window. You would need to destroy the existing label and then add the new instance. But as you can see from my code, the solution is much easier than that: just update the existing label with the new content.