问题
I can't seem to be able to use the function
gtk_label_set_text();
this is what I write:
#include <gtk/gtk.h>
int main(int argc, char *argv[] )
{
gtk_init(&argc, &argv);
GtkWidget *label;
//label
label = gtk_label_new("This is my label");
gtk_label_set_text(label, "I cannot use this func");
if(GTK_IS_LABEL(label)){
g_print("IT IS A LABEL\n");
}else if (GTK_IS_WIDGET(label)){
g_print("well at least its a Widget\n");
}else {
g_print("why is it not a label?! T_T\n");
}
gtk_main();
return 0;
}
it says
passing argument 1 of ‘gtk_label_set_text’ from incompatible pointer type
expected ‘struct GtkLabel *’ but argument is of type ‘struct GtkWidget *’
when I try to compile it. OK. I change it to
GtkLabel *label;
but then it doesn't let me use gtk_label_new(); because the compiler complains with
assignment from incompatible pointer type
then I give up and comment //gtk_label_set_text to ask the program GTK_IS_LABEL(label); and it prints out IT IS A LABEL. I give up for real now and ask you, dear community of Stack Overflow.
回答1:
As it is C code, you have apply a "cast" your pointer since gtk_label_new returns the "base class" or structure:
╰── GtkWidget
╰── GtkMisc
╰── GtkLabel
╰── GtkAccelLabel
The cast is done through a macro (see here) code:
GtkWidget *label;
//label
label = gtk_label_new("This is my label");
gtk_label_set_text(GTK_LABEL (label), "I cannot use this func");
Note: in C++ no need to cast since GtkLabel structure inherits from GtkWidget, you could store label in a GtkLabel directly, but there's no such thing as inheritance in C.
回答2:
As per the [ prototype ] , gtk_label_set_text expects
GtkLabel* as its first parameter, so change
gtk_label_set_text(label, "I cannot use this func");
to
gtk_label_set_text((GtkLabel*)label, "I cannot use this func");
or more conveniently
gtk_label_set_text(GTK_LABEL(label), "I cannot use this func");
In fact GTK_LABEL() macro expands to :
#define GTK_LABEL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_LABEL, GtkLabel))
in the header gtklabel.h.
来源:https://stackoverflow.com/questions/39155120/how-do-i-update-labels-in-gtk-3-0-in-c