sjsam
sjsam

Reputation: 21965

Invalid UTF-8 string

I trying to swap the window title with the label inside the window on keypress.

Below is my code :

#include<gtk/gtk.h>
static gboolean key_press_event(GtkWidget*,GdkEvent*,gpointer);

   int main(int argv, char* argc[])
    {
      GtkWidget *window,*label;
      gtk_init(&argv,&argc);
      window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title(GTK_WINDOW(window),"Sajith");
      gtk_widget_set_size_request(window,300,100);
      label=gtk_label_new("Sam");
      gtk_label_set_selectable(GTK_LABEL(label),TRUE);
      gtk_container_add(GTK_CONTAINER(window),label);
      g_signal_connect(G_OBJECT(window),"key_press_event",
                       G_CALLBACK(key_press_event),label);
      gtk_widget_show_all(window);
      gtk_main();
    }
    static gboolean key_press_event(GtkWidget* window, GdkEvent* event, gpointer label)
    {
      GtkWidget* newlabel;
      newlabel=GTK_LABEL(label);
      const gchar* wtitle=gtk_window_get_title(GTK_WINDOW(window));
      gtk_window_set_title(GTK_WINDOW(window),gtk_label_get_text(GTK_LABEL(newlabel)));
      gtk_label_set_text(GTK_LABEL(newlabel),wtitle);

      /* I am not sure if I could pass wtitle here*/
      return FALSE;
    }

On execution the window title is successfully swapped but the label is not. Also, I get the following warning at the terminal.

(2p1:12005): Pango-WARNING **: Invalid UTF-8 string passed to pango_layout_set_text()

Any help appreciated.

Upvotes: 1

Views: 1058

Answers (1)

user12205
user12205

Reputation: 2702

gtk_window_get_title() returns a static buffer owned by the window. This buffer will have been changed after the gtk_window_set_title() call.

To achieve what you want, you should, in your callback function, create a copy of the string. You can use strdup(), but it may not be available on all platforms. Since you are using GTK+ which depends on GLib, you can use g_strdup(). Example:

gchar* wtitle = g_strdup(gtk_window_get_title(GTK_WINDOW(window)));

Remember to free it before the callback function returns with g_free(wtitle).

As for the return value, since the callback function returns gboolean, you cannot return wtitle. For your case, I don't see any difference between returning TRUE or FALSE, as there aren't any default handlers anyway. If, instead of a label, you are using something like a GtkEntry, then you would return TRUE if you don't want the text in the entry to be replaced by your input key.

Upvotes: 3

Related Questions