The Python Oracle

python GTK3 limit label width

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Python Gtk3 Limit Label Width
01:19 Accepted Answer Score 7
01:43 Answer 2 Score 3
02:30 Thank you

--

Full question
https://stackoverflow.com/questions/2855...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #gtk #label #width #gtk3

#avk47



ACCEPTED ANSWER

Score 7


So here is a solution (still not the exact pixel width) You can use Gtk.Widget.set_halign to force no horizontal expansion.

Here is the part of the code:

    lbl=gtk.Label(label)
    lbl.set_max_width_chars(5)
    lbl.set_ellipsize(pango.EllipsizeMode.END)
    lbl.set_halign(gtk.Align.CENTER)
    self.add(lbl)

This is what it looks like: screeshot of the window

I hope I did not miss anything this time.




ANSWER 2

Score 3


You do have another option: use a custom GtkContainer implementation that limits its children to exact pixel widths. According to Erick Pérez Castellanos on irc.gimp.net/#gtk+, GNOME Contacts has one; here it is. It's in Vala, but it shouldn't be too hard to wrap your head around alongside some reading of the GtkWidget and GtkContainer (and GtkBin) semantics. Unfortunately I do not know how to create new GObjects in Python, sorry.

If you do use the approach in GNOME Contacts, the custom container (which derives from GtkBin, a convenience for single-child GtkContainers) will hold just your GtkLabel, and you add that to the flowbox item's GtkVBox.

Hopefully that helps.