I am facing issue to set background color of selected text in GtkText widget. I tried this way, but it didn't work! can anybody check it ? --
static const char *css =
".one text.selection {"
" all: unset;"
" min-width: 100px;"
" min-height:20px;"
" background-color: blue;"
" outline-color: gray;"
"}";
GtkWidget *w = gtk_text_new ();
gtk_widget_add_css_class (w, "one");
In the GTK4 documentation and GTK-Demo, there are some good examples on the subject:
I took an example from the GTK4 documentation and added it accordingly.
#include"textview-css.h"
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
void activate (GtkApplication *app, gpointer data)
{
GtkWidget *window;
window =gtk_application_window_new(app);
gtk_widget_set_size_request(window,150,150);
GtkWidget *view;
GtkTextBuffer *buffer;
GtkTextIter start, end;
PangoFontDescription *font_desc;
//GdkRGBA rgba;
GtkTextTag *tag;
GtkCssProvider *provider;
GtkStyleContext *context;
GtkStyleContext *context_text;
view = gtk_text_view_new();
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));
gtk_text_buffer_set_text (buffer, "Hello, this is some text", -1);
GtkEntryBuffer *ebuffer;
GtkWidget *text = gtk_text_new();
ebuffer = gtk_text_get_buffer(GTK_TEXT(text));
gtk_entry_buffer_set_text(ebuffer,"This is another text for GtkText.",-1);
gtk_editable_set_editable(GTK_EDITABLE(text),TRUE);
/* Change default font and color throughout the widget */
provider = gtk_css_provider_new ();
gtk_css_provider_load_from_data (provider,
"textview text {"
" font: 15px serif;"
" color: green;"
"}"
".view text selection {" // selected text
" background-color: green;"
" color: red;"
"}"
"text selection {"
" background-color: green;"
" color: red;"
"}",
-1);
context = gtk_widget_get_style_context (view);
gtk_style_context_add_provider (context,
GTK_STYLE_PROVIDER (provider),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
context_text = gtk_widget_get_style_context(text);
gtk_style_context_add_provider (context_text,
GTK_STYLE_PROVIDER (provider),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
/* Change left margin throughout the widget */
gtk_text_view_set_left_margin (GTK_TEXT_VIEW (view), 30);
/* Use a tag to change the color for just one part of the widget */
tag = gtk_text_buffer_create_tag (buffer, "blue_foreground",
"foreground", "blue",
NULL);
gtk_text_buffer_get_iter_at_offset (buffer, &start, 7);
gtk_text_buffer_get_iter_at_offset (buffer, &end, 12);
gtk_text_buffer_apply_tag (buffer, tag, &start, &end);
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL,5);
gtk_box_set_homogeneous(GTK_BOX(box),TRUE);
gtk_box_append(GTK_BOX(box),view);
gtk_box_append(GTK_BOX(box),text);
gtk_window_set_child(GTK_WINDOW(window),box);
gtk_widget_set_visible(window,TRUE);
}```
Please, here is both GtkTextView and only GtkText.
Regards