2008-01-18

A simple wx.grid.Grid example

I've had the opportunity to help Dereje with a wxPython question this week. His question was how to add an image to a cell in a wx.Grid. The wxPython demo and docs are great (really) but are not always the easiest to understand and the wx.Grid examples are a bit over-complicated so I've made an implementation that's as simple as can be. Here goes.

>>> import wx
>>> import wx.grid
>>> class MyApp(wx.App):
... def OnInit(self):
... frame = wx.Frame(None, -1, title = "wx.Grid - Bitmap example")
... grid = wx.grid.Grid(frame)
... grid.CreateGrid(1,1)
... img = wx.Bitmap("python-logo.png", wx.BITMAP_TYPE_PNG)
... imageRenderer = MyImageRenderer(img)
... grid.SetCellRenderer(0,0,imageRenderer)
... grid.SetColSize(0,img.GetWidth()+2)
... grid.SetRowSize(0,img.GetHeight()+2)
... frame.Show(True)
... return True

>>> class MyImageRenderer(wx.grid.PyGridCellRenderer):
... def __init__(self, img):
... wx.grid.PyGridCellRenderer.__init__(self)
... self.img = img
... def Draw(self, grid, attr, dc, rect, row, col, isSelected):
... image = wx.MemoryDC()
... image.SelectObject(self.img)
... dc.SetBackgroundMode(wx.SOLID)
... if isSelected:
... dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID))
... dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
... else:
... dc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID))
... dc.SetPen(wx.Pen(wx.WHITE, 1, wx.SOLID))
... dc.DrawRectangleRect(rect)
... width, height = self.img.GetWidth(), self.img.GetHeight()
... if width > rect.width-2:
... width = rect.width-2
... if height > rect.height-2:
... height = rect.height-2
... dc.Blit(rect.x+1, rect.y+1, width, height, image, 0, 0, wx.COPY, True)

>>> app = MyApp(0)
>>> app.MainLoop()
The above code ought to look something like this:



The class MyImageRenderer is the same as the one from the demo. I modified it slightly so that it loads an image from file rather than from a hex coded string and that you can set the image as a parameter instead of having it defined within the renderer itself.

Inga kommentarer: