Hello,
EDIT: simplified renderer code for better readability
I have a table with floating numbers, that can have a big number of decimals.
I use a custom renderer that write these numbers in scientific format with 3 decimals (plus some other features, background + text coloring).
When I use AutoSizeColumns, the column widths remain unchanged, corresponding to the minimum size of the non-rendered floating numbers with many decimals.
If instead, for the test, I use the existing GridCellFloatRenderer, the columns are properly resized.
Do you have any idea to make the AutoSizeColumns work as intended for my custom renderer?
Thank you.
self.grid = wx.grid.Grid(self.sbox_grid, size=(1000, 800))
self.grid.CreateGrid(self.row_number, self.col_number)
self.grid.SetTable(self.table, takeOwnership=True)
for col in range(4, self.grid.GetNumberCols()):
renderer = MySumReportRenderer(self, precision=3)
attr = wx.grid.GridCellAttr()
attr.SetRenderer(renderer)
attr.SetAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
self.grid.SetColAttr(col, attr)
self.grid.AutoSizeColumns()
class MySumReportRenderer(wx.grid.GridCellRenderer):
def __init__(self, parent, precision=3):
wx.grid.GridCellRenderer.__init__(self)
self.grid = parent.grid
self.cmd = parent.cmd
self.corners = parent.corners
self.precision = precision
self.normalfont = wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
self.boldfont = wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.BOLD)
self.selection_color = self.grid.GetSelectionBackground()
self.sev_color = {
0: 'red',
1: 'darkorange',
2: 'black',
3: 'black',
4: 'black',
}
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
text = grid.GetCellValue(row, col)
dc.SetPen(wx.TRANSPARENT_PEN)
if text == '':
if isSelected:
dc.SetBrush(wx.Brush(self.selection_color, wx.SOLID))
else:
dc.SetBrush(wx.Brush('white', wx.SOLID))
dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
elif text == 'nan':
if isSelected:
dc.SetBrush(wx.Brush(self.selection_color, wx.SOLID))
else:
dc.SetBrush(wx.Brush('gold', wx.SOLID))
dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
dc.SetTextForeground('black')
dc.SetFont(self.normalfont)
dc.DrawLabel(text, rect, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
else:
if isSelected:
dc.SetBrush(wx.Brush(self.selection_color, wx.SOLID))
else:
dc.SetBrush(wx.Brush('white', wx.SOLID))
dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
value = self.grid.GetCellValue(row, col)
_f = '{:.%ie}' % self.precision
formatted_value = _f.format(float(value))
dc.SetTextForeground('black')
dc.SetFont(self.normalfont)
dc.DrawLabel(formatted_value, rect, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
def GetBestSize(self, grid, attr, dc, row, col):
text = grid.GetCellValue(row, col)
dc.SetFont(attr.GetFont())
w, h = dc.GetTextExtent(text)
return wx.Size(w, h)
def Clone(self):
MySumReportRenderer()