gtk +更改按钮使用css

有谁知道如何使用css更改按钮颜色?我需要根据函数是否返回true/false来更改它。 我发现这段代码,但我不能改变按钮的颜色。按钮的颜色变成蓝色。gtk +更改按钮使用css

GdkDisplay *display; 

GdkScreen *screen;

GtkCssProvider *provider;

GtkWidget *testBtn;

//create a button

testBtn = gtk_button_new_with_label("test");

//give button ID

gtk_widget_set_name(GTK_WIDGET(testBtn), "testBtnNeutral");

//Create objects.

provider = gtk_css_provider_new();

display = gdk_display_get_default();

screen = gdk_display_get_default_screen(display);

//Connect screen with provider.

gtk_style_context_add_provider_for_screen(screen,

GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER);

//Give button color.

gtk_css_provider_load_from_data(GTK_CSS_PROVIDER(provider), "#testBtnNeutral {background:blue; color:white} \n #testBtnFail {background:red; color:white} \n #testBtnSuccess {background:green; color:white}", -1 , NULL);

函数,我试图改变按钮的颜色。

static void testFunction(VariablesThatCouldBeUsedInFunctions *StructPointer){ 

if(bTestElectricFunctions){

gtk_widget_set_name(GTK_WIDGET(StructPointer->testBtn), "testBtnSuccess");

//Gtk-CRITICAL **: gtk_widget_set_name: assertion 'GTK_IS_WIDGET (widget)' failed

}

else{

printf("untrue\n");

}

}

回答:

下面的代码片段按预期工作,你可能在你的testFunction或调用者的问题,关键的错误是很清楚的,StructPointer->testBtn是什么,但一个GtkWidget的,也许是NULL

#include <gtk/gtk.h> 

int buttonState = 2;

static void button_cb (GtkWidget *widget, gpointer data)

{

if (buttonState == 0)

gtk_widget_set_name (widget, "btnFail");

else if (buttonState == 1)

gtk_widget_set_name (widget, "btnNeutral");

else

gtk_widget_set_name (widget, "btnSuccess");

buttonState = buttonState == 2 ? 0 : ++buttonState;

}

int main (int argc, char **argv)

{

gtk_init (&argc, &argv);

GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);

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

GtkWidget *button = gtk_button_new_with_label ("Click Me");

gtk_widget_set_name (button, "btnNeutral");

gtk_widget_set_valign (button, GTK_ALIGN_CENTER);

gtk_widget_set_halign (button, GTK_ALIGN_CENTER);

g_signal_connect (button, "clicked", G_CALLBACK (button_cb), NULL);

gtk_container_add (GTK_CONTAINER (window), button);

GtkCssProvider *provider = gtk_css_provider_new();

GdkDisplay *display = gdk_display_get_default();

GdkScreen *screen = gdk_display_get_default_screen (display);

gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_USER);

gtk_css_provider_load_from_data (GTK_CSS_PROVIDER (provider), "#btnNeutral {background:blue; color:white} #btnFail {background:red; color:white} #btnSuccess {background:green; color:white}", -1 , NULL);

gtk_widget_show_all (window);

gtk_main();

return 0;

}

以上是 gtk +更改按钮使用css 的全部内容, 来源链接: utcz.com/qa/263867.html

回到顶部