How to set default font and size for the text buffer

52 Views Asked by At

I just simply want to set a default font using GTK4, but the examples I found don't work.
This code below is what I used and it does absolutely nothing; it doesn't even give me an error. So I have no idea of what I might be doing wrong.

#include <gtk/gtk.h>

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWidget *window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "GTK4 Text Buffer Example");
    gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);

    // Create a text buffer
    GtkTextBuffer *buffer = gtk_text_buffer_new(NULL);

    // Create a text view and set its buffer
    GtkWidget *text_view = gtk_text_view_new_with_buffer(buffer);

    // Set default font and size for the text buffer
    PangoFontDescription *font_desc = pango_font_description_from_string("Cantarell Italic Light 15");
    GtkTextTag *tag = gtk_text_buffer_create_tag(buffer, "default_tag", "font-desc", font_desc, NULL);
    g_object_set(tag, "font-desc", font_desc, NULL);
    pango_font_description_free(font_desc);

    // Create a scrolled window and add the text view
    GtkWidget *scrolled_window = gtk_scrolled_window_new();
    gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scrolled_window), text_view);

    gtk_window_set_child(GTK_WINDOW(window), scrolled_window);

    gtk_window_present(GTK_WINDOW(window));
    //gtk_widget_show(window);
}

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

I want to set a default font and size to text in a text buffer using GTK4 in C.

1

There are 1 best solutions below

1
Kripto On

All types of configuration related to text visualization (font, size, color, etc.) are not made in the Textbuffer, they are made in the TextView. The TextBuffer stores data, how it will be displayed is up to the TextView. To choose these details, use a CSS class that affects the TextView in question or Pango to format the inserted text.