whotheman
whotheman

Reputation: 117

How do I change a label in GTK while the program is running; from a seperate thread

I am building a multi-threaded application which will display weather data and update automatically in C. I got the weather data to refresh and loaded into variables. I am having trouble changing values on my program mid-run. When I use

gtk_label_set_text(GTK_LABEL(wsrc->text2), wsrc->deg);

I get

(out:7604): Gtk-CRITICAL **: gtk_label_set_text: assertion `GTK_IS_LABEL (label)' failed

How do I do this. The call is from a separate thread from main that loops to renew weather data.

Do I use signals to create a trigger to renew weather data. Looking for advice :)

Upvotes: 1

Views: 1429

Answers (1)

Jussi Kukkonen
Jussi Kukkonen

Reputation: 14587

Do not call GTK+ methods from outside it's main thread, period. I know there are workarounds, but 99.99% of the time you really do not want to do it.

What you should do instead is this:

/* in your other thread do this: it will make sure update_text2 will be called in
   GTK+ main thread */
g_main_context_invoke (NULL, update_text2, wsrc);

static gboolean update_text2 (gpointer userdata)
{
    my_obj* wsrc = (my_obj*) userdata;
    gtk_label_set_text(GTK_LABEL(wsrc->text2), wsrc->deg);
    return G_SOURCE_REMOVE;
}

I didn't test that code, and don't know the type of your wsrc pointer but I'm sure you get the drift.

Upvotes: 2

Related Questions