[pygtk] Label & Word Wrapping

Adam Tauno Williams awilliam at whitemice.org
Tue Feb 22 22:02:43 WST 2011


On Tue, 2011-02-22 at 21:13 +0800, Jason Heeris wrote: 
> On 22 February 2011 20:30, Adam Tauno Williams <awilliam at whitemice.org> wrote:
> > available space - just wrap incorrectly.  Any hints for displaying
> > multi-lined / long-lined text in a label more elegantly?
> I think I've had the same problem. You may be interested in this:
> http://stackoverflow.com/questions/1893748/pygtk-dynamic-label-wrapping/1911179#1911179
> ...which I've used with good results.

You get a gold star!  This works.

I put the method -

def label_size_allocate_hack(widget, allocation):
    "Callback which re-allocates the size of a label."
    layout = widget.get_layout()
    lw_old, lh_old = layout.get_size()
    # fixed width labels
    if lw_old / pango.SCALE == allocation.width:
        return
    # set wrap width to the pango.Layout of the labels
    layout.set_width(allocation.width * pango.SCALE)
    lw, lh = layout.get_size()  # lw is unused.
    if lh_old != lh:
        widget.set_size_request(-1, lh / pango.SCALE)

- in my hacks.py file, and then -

from hacks                  import label_size_allocate_hack

...

label = gtk.Label()
label.set_markup('<tt>{0}</tt>'.format(glib.markup_escape_text(annotation['comment'])))
label.set_alignment(0.0, 0.0)
label.set_line_wrap(True)
label.set_selectable(True)
label.connect_after("size-allocate", label_size_allocate_hack)
vbox.pack_end(label, expand=True, fill=True, padding=2)

- and the labels seem to be behave more sanely, at least horizontally.
Now they are jumping up and down vertically within the vbox when the
window is resized.  Hmm.



More information about the pygtk mailing list