Create a ListCtrl with autosized columns (wxPython)
published on Monday, October 5, 2015
When making a GUI with a list control, it is a common requirement to have all text and titles visible by default. At the same time you may want some minimal size for each column and scale them in proportion if the control is resized.
Neither of the wxPython builtin classes ListCtrl or ListView do provide such advanced capability. Although you can specify LIST_AUTOSIZE or LIST_AUTOSIZE_USEHEADER as column size, this leads to a hardly satisfactory experience: either column headers or text may be clipped, depending on which of these constants you choose. Furthermore, using this mechanism naively will lead to all columns just taking minimal space without taking into account global properties of the list control. If the list control is larger than the sum of the column sizes, the columns will appear bunched up on the left leaving empty space on the right of the control which can be quite ugly.
One might hope that another class that is shipped with wxPython might address this problem. Indeed, there is a mixin class called ListCtrlAutoWidthMixin. But beware, this utility only sounds like it would do the right thing but in fact is used for something completely different: resizing the columns to take up all the space when the list control is resized.
The truth is: if you want a list control that shows all its content and doesn't do major any no-nos, you currently have to come up with a custom solution.
I recently had to write a piece of software like that so here I share the result with any interested parties. The module can be downloaded from here and is free to use and modify without limitations.
Note that the code makes some opinionated choices how rows must be added to or removed from the list control. The API is designed with the goal to separate the tasks of formatting items from the management of list membership. This is of course secondary and it shouldn't be too hard to extract only the auto-sizing functionality without having to use the suggested data model.