Skip to content

Wrapping Static Text in wxPython

In addition to packing for NYC this morning, I’m working on getting a new release of ccTag out the door. I’m working on lots of UI issues at the moment, and part of that relates to “wxPython’s”:http://wxpython.org StaticText widget (“Label” to you recovering Win32 programmers). Unfortunately, the StaticText widget doesn’t support automagic word-wrapping, so I’ve derived a new class which may be of interest to others.

StaticWrapText acts like a regular StaticText widget, with the exception that it will attempt to word wrap it’s contents as it’s resized. This makes it much easier to use a single XRC across platforms where font sizes, etc may impact line breaks in a normal StaticText widget. You can find the source in “stext.py”:http://yergler.net/projects/stext/stext_py.txt. The source includes the widget class, an XRC resource handler, and a very simple sample which will execute when you run stext.py directly. The sample demonstrates how to use the XRC resource handler.

There are a couple areas that could use improvement. Currently the resize is only called when the widget receives an EVT_SIZE event, so it’s possible that your app could start with the text unwrapped. I’ve worked around this by manually calling OnSize on the widget when I create it. Not an ideal solution, but one that works for now.

Second, the word wrap algorithm I wrote is, well, stupid. But it was quick and dirty, so I ran with it. I’m open to suggestions and improvements.

Categories: development.

Comment Feed

2 Responses

  1. This text wrapping was a life-saver. Thank you for making 3:30 am programming slightly less painful.

  2. Nice indeed! Also of note is that a wx.StaticText (at least in recent versions) has a Wrap(pixels) method, which ended up being what I wanted.

    Wrap() will do the trick when throwing some text in a non-resizable control/dialog which you Fit() after adding everything.

    However it seems like a smarter control like you’ve created is necessary when the size is dynamic.