Search code examples
pythonwxpythonwxwidgets

How can I highlight individual characters in a cell of a wx.Grid?


I'm currently writing a proteomic coverage analysis tool (if you don't know what that is, it looks something like this. Basically, I have to present a large quantity of apparently random text, and highlight various parts of it. I'm using a wx.Grid with the cell outlines disabled to present the text in an organized fashion (because wx.RichTextCtrls fail to properly monospace highlighted text, sigh.) However, while among the many features of wx.Grids (and wx.XLSGrids, etc.) there are options to highlight entire cells, I can't find a way to highlight specific text within a cell. Is there a way to achieve this?


Solution

  • Maybe. The closest thing I'm aware of is the Custom Renderer in the wxPython demo for the Grid widget. Looking at the source, it would appear to be using DC to draw the text with different colors. Here's a snippet from the demo:

    class MyCustomRenderer(gridlib.PyGridCellRenderer):
        def __init__(self):
            gridlib.PyGridCellRenderer.__init__(self)
    
        def Draw(self, grid, attr, dc, rect, row, col, isSelected):
            dc.SetBackgroundMode(wx.SOLID)
            dc.SetBrush(wx.Brush(wx.BLACK, wx.SOLID))
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.DrawRectangleRect(rect)
    
            dc.SetBackgroundMode(wx.TRANSPARENT)
            dc.SetFont(attr.GetFont())
    
            text = grid.GetCellValue(row, col)
            colors = ["RED", "WHITE", "SKY BLUE"]
            x = rect.x + 1
            y = rect.y + 1
    
            for ch in text:
                dc.SetTextForeground(random.choice(colors))
                dc.DrawText(ch, x, y)
                w, h = dc.GetTextExtent(ch)
                x = x + w
                if x > rect.right - 5:
                    break
    

    Hopefully that will help you get started. If that does not work for you, then you may have to come up with your own renderer.