Search code examples
cwidgetlabelalignmentgtk3

How to align a GtkWidget label in the center of its GtkWidget layout in C with GTK3?


I have the following code, and I'm struggling to align the label in the center of its parent (layout), but nothing has worked for me:

int main(int argc, char ** argv){
    GtkWidget *window;
    GtkWidget *layout;
    GtkWidget *label;

    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), 1024, 600);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

    layout = gtk_layout_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER (window), layout);

    label = gtk_label_new(NULL);
    gtk_label_set_text(GTK_LABEL(label), "SOME TEXT");
    gtk_layout_put(GTK_LAYOUT(layout), label, 0, 0);

    // Here I'm trying to align my label to the center,
    // but it doesn't work with any of the three functions
    gtk_widget_set_halign(label, GTK_ALIGN_CENTER);
    //gtk_label_set_xalign(GTK_LABEL(label), GTK_ALIGN_CENTER);
    //gtk_misc_set_alignment(GTK_MISC(label), 0.5f, 0.5f);




    gtk_widget_show_all(window);
    gtk_main();
    return 0;
}

I have also tryied some other functions that I could find in the GENOME documentation and other SO questions but they are mostly deprecated, or also doesn't work. At this point, as I'm working with GTK3, the recommended way seems to be with:

gtk_widget_set_halign(label, GTK_ALIGN_CENTER);

But it is not working. The label is still at the position I put it with:

gtk_layout_put(GTK_LAYOUT(layout), label, 512, 300);

The code compiles without any errors or warnings.


Solution

  • GtkLayout, like its relative GtkFixed, is kind of a last-resort container that you use when none of the other containers will work for your purpose. It just puts widgets where you specify them. So, the horizontal alignment APIs will not work. With GtkLayout, you have to calculate the alignment yourself.

    I would recommend using GtkGrid or one of the other, more full-featured containers.