Setting text color of GtkEnty

I’m trying to set the text color to red in a GtkEntry widget using GTK4. However, no matter what I try, the background also turns into a transparent red. Does anyone know how to set only the text color to red without affecting the background? Here’s the code I’m currently using:

GtkCssProvider* provider = gtk_css_provider_new();
const char* redColor = “entry{color:#FF0000;}”;
gtk_css_provider_load_from_string(provider, redColor);
// Get the style context and add the CSS provider
GtkWidget* entry = GTK_WIDGET(pCtrl->getHandle());
GtkStyleContext* context = gtk_widget_get_style_context(entry);
gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER);

This is how it looks:
image

Hi,

Are you using libadwaita?
If yes, it’s normal, they automatically recolor the background based on the foreground color.

An easy way to circumvent this is to apply the color to the embedded GtkText:

entry > text {
	color: red;
}

By the way, avoid using the widget’s style context, it’s deprecated, and doesn’t properly cascade to children. Apply the CSS to the display instead.
(for the details, there are dozens of topics on this forum about how to do this)

Unfortunately, this approach doesn’t work. In this case, the text remains unchanged. And yes, I am using Adwaita.

If I set the CSS to control the display, it becomes more challenging to allow users to choose arbitrary text colors. I would need to create tag names with embedded colors to accommodate this, but it’s manageable.

Yes, if you use gtk_widget_get_style_context then the CSS won’t cascade to the GtkText embedded child. That’s why you have use the display’s context instead.

1 Like

Excellent! It works now. Thanks!!

1 Like

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