views:

39

answers:

1

I have a WxPython frame containing a single item, such as:

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text = wx.StaticText(self, label='Panel 1')

I have a frame containing several panels, including this one, and dimensions are ruled by sizers. I would like this StaticText to expand. Using a BoxSizer containing just the text and setting the wx.EXPAND flag does the trick, but it seems silly to use a sizer just for one item.

Any simpler solution?

(I could just add the StaticText to the parent frame's sizer directly, but for my design it makes more sense to start with a frame directly.)


I just realized that when creating a BoxSizer with one item doesn't work with wx.VERTICAL:

class Panel1(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.BackgroundColour = 'red'
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer = sizer
        self.list = wx.ListBox(self, choices=[str(i) for i in xrange(100)])
        sizer.Add(self.list, 0, wx.EXPAND)
        sizer.Fit(self)

Of course it's ok with one item, but what if I want to add an item vertically later and still make both of them expand (e.g. when the user's window is expanded)?

Edit: ah, I just found out that proportion must be used in order to make boxsizers grow in both ways. (i.e., replace 0 with 1 in BoxSizer.Add's call.)

+2  A: 

A wx.Frame will automatically do this if it only has one child. However, a wx.Panel will not do this automatically. You're stuck using a sizer. If you find yourself doing it a lot, just make a convenience function:

def expanded(widget, padding=0):
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(widget, 1, wx.EXPAND|wx.ALL, padding)
    return sizer

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text = wx.StaticText(self, label='Panel 1')
        self.SetSizer(expanded(self.text))

I threw the padding attribute in there as an extra bonus. Feel free to use it or ditch it.

FogleBird
Thanks. Do you have any idea regarding my edit?
Bastien Léonard
Yep, proportion makes it grow in the sizer's direction. wx.EXPAND makes it expand to fill the other direction. Use them both to grow in both directions.
FogleBird