gtk +使用css更改按钮

问题描述 投票:0回答:1

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

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");
    }
}
css button colors gtk
1个回答
0
投票

下面的片段按预期工作,你可能在你的testFunction或它的调用者有问题,CRITICAL错误非常清楚,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;
}
© www.soinside.com 2019 - 2024. All rights reserved.