Search code examples
pythonpython-3.xwxpythonwxwidgets

Set column width to maximum content or header width for a wx.dataview.DataViewListCtrl


I try to set up a wx.dataview.DataViewListCtrl. I have multiple columns with text content. Some Entries of the first column are wider than the selected default width. They are cut off. I could set the column width by hand but I like to set it up automatically to the maximum content or header width. Is there an automated way to do so? If not, how can I calculate the ideal width. I'm on Ubuntu Linux. The used backend is gtk. A C++ answer using wxDataViewListCtrl could help, too. I'm able to translate it.


Solution

  • You can determine the column size knowing which is the longest size of each text value stored in its cells programmatically and assign the widest value to this column width.

    For this, you must create a font object:

    # Example font:
    font = wx.Font(pointSize = 10, family = wx.DEFAULT, style = wx.NORMAL, weight wx.NORMAL, faceName = 'Consolas')
    
    # Get the screen display control and set the font:
    dc = wx.ScreenDC()
    dc.SetFont(font)
    
    # Gets the width and height of that text with this font:
    w,h = dc.GetTextExtent("hello world")
    

    You must calculate this for each text you enter in the cell of that column, remembering the largest of all those values. After completing the ListView, you will already have a reference for the column size.