Search code examples
pythonwxpythonwxwidgetswidthlistctrl

How can I get the width of a wx.ListCtrl and its column name?


I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)

How can I find out how wide the titles and elements of my list will be rendered?


Solution

  • Yes, you would have to make this yourself for wx.ListCtrl and I'm not sure it would be easy (or elegant) to do right.

    Consider using a wx.Grid, here is a small example to get you going:

    import wx, wx.grid
    
    class GridData(wx.grid.PyGridTableBase):
        _cols = "This is a long column name,b,c".split(",")
        _data = [
            "1 2 3".split(),
            "4,5,And here is a long cell value".split(","),
            "7 8 9".split()
        ]
    
        def GetColLabelValue(self, col):
            return self._cols[col]
    
        def GetNumberRows(self):
            return len(self._data)
    
        def GetNumberCols(self):
            return len(self._cols)
    
        def GetValue(self, row, col):
            return self._data[row][col]
    
    
    class Test(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None)
            grid = wx.grid.Grid(self)
            grid.SetTable(GridData())
            grid.EnableEditing(False)
            grid.SetSelectionMode(wx.grid.Grid.SelectRows)
            grid.SetRowLabelSize(0)
            grid.AutoSizeColumns()
    
    
    app = wx.PySimpleApp()
    app.TopWindow = Test()
    app.TopWindow.Show()
    app.MainLoop()