wxPython: Items in BoxSizer don't expand horizontally, only vertically

Peter Horne picture Peter Horne · Aug 15, 2009 · Viewed 8k times · Source

I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functions correctly vertically, but not horizontally.

The following code demonstrates the problem:

#! /usr/bin/env python

import wx
import webbrowser

class App(wx.App):


    def OnInit(self):
       frame = MainFrame()
       frame.Show()
       self.SetTopWindow(frame)
       return True


class MainFrame(wx.Frame):

    title = 'Title'


    def __init__(self):
        wx.Frame.__init__(self, None, -1, self.title)

        panel = wx.Panel(self)

        #icon = wx.Icon('icon.png', wx.BITMAP_TYPE_PNG)
        #self.SetIcon(icon)

        sizer = wx.FlexGridSizer(rows=2, cols=1, vgap=10, hgap=10)

        button1 = wx.Button(panel, -1, 'BUTTON')
        sizer.Add(button1, 0, wx.EXPAND)

        buttonSizer = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=5)

        buttonDelete = wx.Button(panel, -1, 'Delete')
        buttonSizer.Add(buttonDelete, 0, 0)

        buttonEdit = wx.Button(panel, -1, 'Edit')
        buttonSizer.Add(buttonEdit, 0, 0)

        buttonNew = wx.Button(panel, -1, 'New')
        buttonSizer.Add(buttonNew, 0, 0)

        buttonSizer.AddGrowableCol(0, 0)

        sizer.Add(buttonSizer, 0, wx.EXPAND|wx.HORIZONTAL)

        sizer.AddGrowableCol(0, 0)
        sizer.AddGrowableRow(0, 0)

        mainSizer = wx.BoxSizer(wx.EXPAND)
        mainSizer.Add(sizer, 0, wx.EXPAND|wx.ALL, 10)

        #panel.SetSizerAndFit(sizer)
        #sizer.SetSizeHints(self)
        panel.SetSizerAndFit(mainSizer)
        mainSizer.SetSizeHints(self)


if __name__ == '__main__':
    app = App(False)
    app.MainLoop()

Commenting out lines 57 and 58 and uncommenting lines 55 and 56 removes the extra BoxSizer and shows how I expect everything to function (without the whitespace of course).

I am completely stuck with this problem and still have no clue as to how to fix it.

Answer

FogleBird picture FogleBird · Aug 15, 2009

First of all, you're passing some flags incorrectly. BoxSizer takes wx.HORIZONTAL or wx.VERTICAL, not wx.EXPAND. sizer.Add does not take wx.HORIZONTAL.

If you have a VERTICAL BoxSizer, wx.EXPAND will make the control fill horizontally, while a proportion of 1 or more (second argument to Add) will make the control fill vertically. It's the opposite for HORIZONTAL BoxSizers.

sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget1, 0, wx.EXPAND)
sizer.Add(widget2, 1)

widget1 will expand horizontally. widget2 will expand vertically.

If you put a sizer in another sizer, you need to be sure to have its proportion and EXPAND flags set so that its insides will grow how you want them to.

I'll leave the rest to you.