1

I am trying to add a label to a GTK3 window and then set the font size of the label. Here is my attempt:

#include <gtk/gtk.h>

static void
add_label (GtkWidget* window, gchar *text)
{

    GtkWidget *label = gtk_label_new(text);
    PangoAttrList *attrlist = pango_attr_list_new();
    PangoAttribute *attr = pango_attr_size_new_absolute(20);
    pango_attr_list_insert(attrlist, attr);
    gtk_label_set_attributes(GTK_LABEL(label), attrlist);
    pango_attr_list_unref(attrlist);
    gtk_container_add (GTK_CONTAINER (window), label);
}

static void
activate (GtkApplication* app,
          gpointer        user_data)
{
    GtkWidget *window;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window1");
    gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
    add_label( window, "Hello world" );
    gtk_widget_show_all (window);
}

int
main (int argc, char **argv) 
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ( "org.gtk.example", G_APPLICATION_FLAGS_NONE );
    g_signal_connect( app, "activate", G_CALLBACK(activate), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref (app);

    return status;
}

This does not produce any label at all. If I comment out the line:

gtk_label_set_attributes(GTK_LABEL(label), attrlist);

the label shows up, but the font size is not set.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174

1 Answers1

2

I think PANGO_SCALE is missing here.

PangoAttribute *attr = pango_attr_size_new_absolute(20 * PANGO_SCALE);

This should give you the desired result:

enter image description here

GTK 1.2.6 fanboy
  • 839
  • 1
  • 5
  • 20
  • Great, this works! I was not aware of the Pango scaling. – Håkon Hægland Dec 29 '17 at 16:30
  • 2
    [The documentation](https://developer.gnome.org/pango/stable/pango-Text-Attributes.html#pango-attr-size-new-absolute) does say `size: the font size, in PANGO_SCALEths of a device unit.`, so that'll be why you need to multiply up. – underscore_d Dec 29 '17 at 16:34