Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set max width of GtkLabel properly?

I am writing a Vala application and using GtkLabels' in it. Problem is, I made my main window not resizable and when I'm adding labels with a long text to it, the window gets very big (when the window was resizable, all labels were fitting perfectly). I tried to set_max_width_chars() to some value and it kind of works, but I guess this isn't the right way to do it (because users' fonts may vary and this won't work with fonts sizes that are different from mine).

So, the question: how to do it the right way?

like image 316
serge1peshcoff Avatar asked Dec 13 '14 19:12

serge1peshcoff


1 Answers

You can't directly limit the width of a label (other than max-width-chars, which is in characters, not in pixels), but you can limit it indirectly by influencing the size of the box that contains it and by setting 4 not immediately obvious properties of the label.

Consider the following scenario:

  • You have a box
  • You have multiple subboxes with widgets in the box
  • All widgets have their natural size, that size can be bigger or smaller, but it's always reasonable

RESULT:

  • box is expanded as needed for all widgets to fit

Now comes the label:

  • There are label (maybe multiple labels) in one/some of the boxes
  • Label text can be anything, including a very long string
  • You didn't tell the label to wrap into multiple lines (this is the default)

RESULT:

  • box is expanded to ridiculous width to accommodate the label (other widgets are much smaller)

In this scenario the following fix is available:

  • Set max-width-chars of the label to a small positive value (1 would work just fine)
  • Set ellipsize of the label to any value other than PANGO_ELLIPSIZE_NONE
  • Set hexpand of the label to TRUE (or set expand of the label to TRUE, with obvious consequences)
  • Set fill of the label (as a child of the subbox it's in) to TRUE (if vexpand is also TRUE, you might want to restrict its filling to horizontal direction only)

RESULT:

  • width of the box depends only on widths of the other widgets, and is unaffected by the length of the text of the label
  • the label is expanded to fill the available space (the space depends only on the width of the box, see above), regardless of how small the positive value of max-width-chars is
  • if the label text is so long that it doesn't fit in the available space, it will be ellipsized

This works on labels and other text widgets that have ellipsize and max-width-chars (such as GtkCellRendererText inside a GtkTreeView).

Tested with GTK+-3.18.2

like image 102
LRN Avatar answered Sep 22 '22 11:09

LRN