Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left align a Gtk Label when its width is set by GtkSizeGroup

I have labels that should be left aligned and should all have the same width. I'm using a GtkSizeGroup to achieve the sizing (because the labels don't all have the same parent). Unfortunately this seems to break alignment: With the below code the labels align horizontally in the middle even though I ask for GTK_ALIGN_START. If I remove the sizegroup the labels align to start as they should.

/* gcc `pkg-config --libs --cflags gtk+-3.0` label-align-test.c */
#include <gtk/gtk.h>

int main(int argc, char **argv)
{
  GtkSizeGroup *group;
  GtkWidget *window, *grid, *label1, *label2;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  grid = gtk_grid_new ();
  gtk_container_add (GTK_CONTAINER (window), grid);

  label1 = gtk_label_new ("label 1");
  gtk_widget_set_halign (label1, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (grid), label1,
                           NULL, GTK_POS_BOTTOM,
                           1, 1);

  label2 = gtk_label_new ("label 2 with longer text");
  gtk_widget_set_halign (label2, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (grid), label2,
                           label1, GTK_POS_BOTTOM,
                           1, 1);

  group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
  gtk_size_group_add_widget (group, label1);
  gtk_size_group_add_widget (group, label2);

  g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);

  gtk_widget_show_all (window);

  gtk_main ();

  return 0;
}

Is there something I'm missing or is this a bug?

I'm testing with GTK+ 3.13.6. I realize that the example doesn't need the sizegroup but in the real code the labels have different parents so it is needed. I can work around this problem by adding containers around the labels, and putting the containers in to the size group: then the labels start aligning correctly as well.

like image 883
Jussi Kukkonen Avatar asked Jul 28 '14 11:07

Jussi Kukkonen


2 Answers

I dont know if it makes a difference, however it's worth a try:

Did you try to use gtk_label_set_xalign (label1, 0.0) instead of gtk_widget_set_halign (label1, GTK_ALIGN_START) ?

like image 124
Alex Avatar answered Nov 05 '22 05:11

Alex


This was indeed a unfinished feature: Before GTK+ 3.16 the most simple solution was still to use gtk_misc_set_alignment (GTK_MISC (label1), 0.0, 0.5); even though it was deprecated.

As Alex mentions in the other answer gtk_label_set_xalign (label1, 0.0) is a good solution in modern GTK+ (>= 3.16).

like image 39
Jussi Kukkonen Avatar answered Nov 05 '22 07:11

Jussi Kukkonen