Page 1 of 1

Auto size (stretch) last column of a wxGrid

Posted: Mon Jun 01, 2015 8:32 pm
by iwbnwif
One of the nice features of a wxDataViewCtrl and its derivatives is that the last column automatically resizes so that there is no blank space.

Unfortunately the wxGrid doesn't have a similar feature. Whilst this is somewhat understandable because the intended use of wxGrid is not really to display a list of data, it is a very flexible control and implements some features (notably displaying tooltips on cell hovering) that are useful for lists.

The following is a simple way of stretching the last column of a wxGrid to fill the full width.

I have only been able to test it so far on wxGTK (Ubuntu 14.04) and welcome any improvements, in particular the bind / unbind calls. There are also a few oddities, such as it doesn't always size properly on first creation and it will probably try to unhide the last column if it is hidden.

StretchGrid.h

Code: Select all

#include <wx/grid.h>

class StretchGrid : public wxGrid
{
public:
    StretchGrid (wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
	       long style = wxWANTS_CHARS, const wxString& name = wxGridNameStr);
    ~StretchGrid ();
    
protected:
    void OnGridWindowSize (wxSizeEvent& event);
    void OnColHeaderSize (wxGridSizeEvent& event);
    void AutoSizeLastCol ();
};
StretchGrid.cpp

Code: Select all

StretchGrid::StretchGrid (wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) :
			wxGrid (parent, id, pos, size, style, name)
{
    GetGridWindow()->Bind (wxEVT_SIZE, &StretchGrid::OnGridWindowSize, this);
    Bind (wxEVT_GRID_COL_SIZE, &StretchGrid::OnColHeaderSize, this);
}

StretchGrid::~StretchGrid()
{
    GetGridWindow()->Unbind (wxEVT_SIZE, &StretchGrid::OnGridWindowSize, this);
    Unbind (wxEVT_GRID_COL_SIZE, &StretchGrid::OnColHeaderSize, this);
}

void StretchGrid::OnGridWindowSize (wxSizeEvent& event)
{
    if (GetNumberCols() > 0)
        AutoSizeLastCol ();
}

void StretchGrid::OnColHeaderSize (wxGridSizeEvent& event)
{
    if (GetNumberCols() > 0)
        AutoSizeLastCol ();
}

void StretchGrid::AutoSizeLastCol ()
{
    int colWidths = 0;
    
    for (int i = 0; i < GetNumberCols() - 1; i++)
        colWidths += GetColWidth (i);
    
    int finalColWidth = GetGridWindow()->GetSize().x - colWidths;
    
    if (finalColWidth > 80)
        SetColSize (GetNumberCols() - 1, finalColWidth);
    else
        SetColSize (GetNumberCols() - 1, 80);
}