Search code examples
pythonwxpythonsizerwxnotebookwxgrid

How to size a panel to fit a grid


Here is the simplest example I can make of what I am trying to do. It is a grid inside a panel:

#!/usr/bin/env python

import wx
import wx.grid

app = wx.App(False)  

class InfoPane(wx.grid.Grid):
    def __init__(self, parent):
        wx.grid.Grid.__init__(self, parent)

        # Set up the presentation
        self.SetRowLabelSize(0)
        self.CreateGrid(1, 6)

        self.SetColLabelAlignment( wx.ALIGN_LEFT, wx.ALIGN_CENTRE )
        self.SetColLabelValue(0, "Name")
        self.SetColLabelValue(1, "Status")
        self.SetColLabelValue(2, "")
        self.SetColLabelValue(3, "File")
        self.SetColLabelValue(4, "Last Action")
        self.SetColLabelValue(5, "Other Info")

frame = wx.Frame(None)
panel = wx.Panel(frame)
info_pane = InfoPane(panel)

note_sizer = wx.BoxSizer()
note_sizer.Add(info_pane, 1, wx.EXPAND)

panel.SetSizerAndFit(note_sizer)
frame.Show()

app.MainLoop()

I want the whole thing to size itself so that the contents of the grid are all visible. What happens at the moment is this:

screenie

(note: edit - I took the notebook out, for even more simplification, the result is the same looking)

Ideas? Thanks!


Solution

  • If you add a sizer to the frame when you call the fit method on the frame it will size to its children.

    #!/usr/bin/env python
    
    import wx
    import wx.grid
    
    app = wx.App(False)
    
    
    class InfoPane(wx.grid.Grid):
        def __init__(self, parent):
            wx.grid.Grid.__init__(self, parent)
    
            # Set up the presentation
            self.SetRowLabelSize(0)
            self.CreateGrid(1, 6)
    
            self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
            self.SetColLabelValue(0, "Name")
            self.SetColLabelValue(1, "Status")
            self.SetColLabelValue(2, "")
            self.SetColLabelValue(3, "File")
            self.SetColLabelValue(4, "Last Action")
            self.SetColLabelValue(5, "Other Info")
    
    frame = wx.Frame(None)
    panel = wx.Panel(frame)
    info_pane = InfoPane(panel)
    
    note_sizer = wx.BoxSizer()
    note_sizer.Add(info_pane, 1, wx.EXPAND)
    
    panel.SetSizer(note_sizer)
    frame_sizer = wx.BoxSizer(wx.VERTICAL)
    frame_sizer.Add(panel, 1, wx.EXPAND)
    frame.SetSizerAndFit(frame_sizer)
    frame.Show()
    
    app.MainLoop()