Question

I am trying:

tstring subItemText;
    CDC* pDc = GetListCtrl().GetDC(); 
    for (int row = GetItemCount() - 1; row >= 0; --row) 
    {
      subItemText = _T("");
      for (int col = 0; col < NumCol; ++col)  
      {
        subItemText = this->GetSubItemString( GetItemData(row), col);
        CSize sz; 
        // get length of the string in logical units, by default 1 unit == 1 pixel, type of font is accounted
        sz = pDc->GetOutputTextExtent(subItemText.c_str());
        if (static_cast<int>(sz.cx) > ColWidth[col])
          ColWidth[col] = sz.cx; 
      }
    } 
    GetListCtrl().ReleaseDC (pDc);
    for (int col = 0; col < NumCol; ++col) 
    {
      SetColumnWidth(col, ColWidth[col]);
    }

As result width of the column is on 20/30% larger than one of the largest string in that column. I want that width of column will be equal to width of string with max length.

Thanks in advance!

Was it helpful?

Solution

This is probably because you didn't select the correct font into the device context. Try this :

    tstring subItemText;
    CDC* pDc = GetListCtrl().GetDC(); 

    CFont *normalfont = GetListCtrl().GetFont() ;
    CFont *oldfont = pDc->SelectObject(normalfont) ;

    for (int row = GetItemCount() - 1; row >= 0; --row) 
    {
      subItemText = _T("");
      for (int col = 0; col < NumCol; ++col)  
      {
        subItemText = this->GetSubItemString( GetItemData(row), col);
        CSize sz; 
        // get length of the string in logical units, by default 1 unit == 1 pixel, type of font is accounted
        sz = pDc->GetOutputTextExtent(subItemText.c_str());
        if (static_cast<int>(sz.cx) > ColWidth[col])
          ColWidth[col] = sz.cx; 
      }
    } 

    pDc->SelectObject(oldfont) ;

    GetListCtrl().ReleaseDC (pDc);
    for (int col = 0; col < NumCol; ++col) 
    {
      SetColumnWidth(col, ColWidth[col]);
    }

OTHER TIPS

I think all you need is this:

SetColumnWidth(col, LVSCW_AUTOSIZE);

In my projects, I derive my own class from CListCtrl and use the following function

void CMyListCtrl::AutoSizeColumnWidths()
{
    // size column widths to content
    int nNumColumns = GetHeaderCtrl()->GetItemCount();

    // for all columns ...
    for (int i = 0; i < nColumnCount; i++)
    {
        // find max of content vs header
        SetColumnWidth(i, LVSCW_AUTOSIZE);
        int nColumnWidth = GetColumnWidth(i);
        SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
        int nHeaderWidth = GetColumnWidth(i); 

        // set width to max 
        SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));
    }
    SetRedraw(TRUE);
} 

This makes sure that columns with no content still get sized according to the header text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top