How to set the max width of the GtkLabel correctly?

I am writing a Vala app and using GtkLabels' in it. The problem is that I made my main window non-mutable, and when I add long text labels to it, the window gets very large (when the window was mutable, all the labels fit perfectly). I tried using set_max_width_chars()

for some value and it seems to work, but I think this is the wrong way to do it (since users' fonts may be different and it won't work with font sizes other than mine).

So the question is: how to do it right?

+3


source to share


2 answers


You cannot directly limit the width of the label (other than max-width-chars

which is in characters, not pixels), but you can limit it indirectly by affecting the size of the box that contains it and by setting 4 the not immediately obvious properties of the label.

Consider the following scenario:

  • You have a field
  • You have multiple plugins with widgets in the box
  • All widgets have their natural size, the size can be larger or smaller, but it is always reasonable

RESULT:



  • the field expands as needed for all widgets matching

Now comes the label:

  • One or more boxes have a label (possibly multiple labels)
  • The label text can be anything, including a very long string
  • You did not specify a label on multiple lines (this is the default)

RESULT:



  • the box expands to a ridiculous width to accommodate the shortcut (other widgets are much smaller).

In this case, the following fix is โ€‹โ€‹available:

  • Set max-width-chars

    labels to a small positive value ( 1

    will work fine)
  • Set ellipsize

    labels to any value other thanPANGO_ELLIPSIZE_NONE

  • Set hexpand

    labels to TRUE

    (or set expand

    labels to, TRUE

    with obvious consequences)
  • Set the fill

    labels (as a child of this sub-window) to TRUE

    (if vexpand

    also TRUE

    , you can restrict it to fill only in the horizontal direction)

RESULT:



  • the width of the window depends only on the width of other widgets and does not depend on the length of the label text
  • the label expands to fill the available space (space only depends on the window width, see above), no matter how small the positive value is max-width-chars

  • If the label text is so long that it doesn't fit in the available space, it will be ellipsed

This works with labels and other text widgets with ellipsize

and max-width-chars

( GtkCellRendererText

inside for example GtkTreeView

).

Tested by GTK + -3.18.2

+4


source


I think your labels should be placed in containers and the containing containers should be sized appropriately. If this is not helpful to you, you may want to consider posting a screenshot to better understand your requirements.



0


source







All Articles