Afternoon All,
Just thought I'd share this, as it's something that caused me quite a
bit of frustration, and when I was searching for a solution there were
plenty of other people asking the same question.
As myself and other users discovered, wx.Grids within sizers have a
tendency to have some margin bleed unless they meet very specific size
criteria. There are various hacks to try and get past this, all of
which I've found only partially successful - trying to disable margins
(doesn't seem to work), computationally jiggling the size, setting
sizer hints to prevent resizing, etc.
Here's my take - set the default cell background colour of the grid to
the same colour as your background panel, then set the background
colour of each individual cell back to white. The unwanted bleed/
border occurs in the default colour, which in this case is invisible,
giving your grid a nice crisp edge.
On Win32, the system's default panel colour can be got using
wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE) - this includes any
customisation or hi-vis themes the user may have, so it's
accessibility friendly.
Setting the individual cell colours can either be done using the
wx.Grid method SetCellBackgroundColour(row, col, colour), or (more
elegantly) by passing an attribute via the GetAttr method of a
PyGridTableBase. Giving each cell a non-default attribute does create
an overhead, but unless you're re-implementing Excel, you'll probably
get away with it.
Here's a simple demo implementation using SetCellBackgroundColour.
I've only tested this on Win32, but I'd be interested to know if it
helps on other platforms.
Cheers,
Alex
···
---------------------------------------------------------------------------------------------------------------
import wx
import wx.grid
class GridPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
mainsizer = wx.BoxSizer(wx.HORIZONTAL)
mygrid = wx.grid.Grid(self, wx.ID_ANY)
mygrid.CreateGrid(10,2)
# Here's the secret sauce. Try commenting/uncommenting these lines
to see a comparison
panelcolour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)
mygrid.SetDefaultCellBackgroundColour(panelcolour)
for row in range(0,10):
for col in range(0,2):
mygrid.SetCellBackgroundColour(row, col, wx.WHITE)
mainsizer.Add(mygrid, 0, wx.ALL, 10)
self.SetSizerAndFit(mainsizer)
myapp = wx.PySimpleApp()
myframe = wx.Frame(None, wx.ID_ANY)
mypanel = GridPanel(myframe, wx.ID_ANY)
myframe.Show()
myapp.MainLoop()