GTK4 C change color text of button


please I need help how to proramically change color of text at button.

I have prepated attribut:

PangoAttribute *textColor = pango_attr_foreground_new(65535,0,0);

and I am trying get label from button:

GtkWidget *button =  gtk_button_new_with_label("button text");
GtkWidget *buttonsLabel = gtk_button_get_child(GTK_BUTTON(button));

and I want now change color with

gtk_label_set_attributes(GTK_LABEL(buttonsLabel), textColor);

but I receive error and app crashs:

Unauthorized memory access (SIGSEGV) (core dumped [memory image saved])

thanks a lot

I wonder that your C fragments compile successfully.

I think for setting attributes, we have to provide attribute lists. For example, in Gtk.Label.set_attributes the second parameter is a PangoAttrList. Used like

OK, here is the complete homework for you:

// gcc -Wall button.c -o buton `pkg-config --cflags --libs gtk4`
#include <gtk/gtk.h>

static void
print_hello (GtkWidget *widget, gpointer data)
  g_print ("Hello World\n");

static void
activate (GtkApplication *app, gpointer user_data)
  GtkWidget *window;
  GtkWidget *button;
  GtkWidget *box;
  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
  gtk_window_set_child (GTK_WINDOW (window), box);
  button = gtk_button_new_with_label ("Hello World");
  GtkWidget *label = gtk_button_get_child(GTK_BUTTON(button));
  PangoAttribute *textColor = pango_attr_foreground_new(65535,0,0);
  PangoAttribute *const SizeAttr = pango_attr_size_new(72*PANGO_SCALE);
  PangoAttrList *const Attrs = pango_attr_list_new();
  pango_attr_list_insert(Attrs, SizeAttr);
  pango_attr_list_insert(Attrs, textColor);
  gtk_label_set_attributes((GtkLabel *)label, Attrs);
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);
  gtk_box_append (GTK_BOX (box), button);
  gtk_window_present (GTK_WINDOW (window));

main (int argc, char **argv)
  GtkApplication *app;
  int status;
  app = gtk_application_new ("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);
  return status;

gtk_label_set_attributes() takes a PangoAttrList, not a PangoAttribute, so you code is not valid. You should have seen a bunch of compiler warnings that would have told you about it.

In general, though, if you want to change the color of the entire text of a label, you should use a CSS class and load a CSS fragment. Using Pango attributes is only ever useful if you’re trying to assign attributes to regions of the text.

thanks for all replys! You have right. I have tried maximal simplify my question and I have forgot copy few rows…

StefanSalewski’s answer helsps a lot!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.