2013-05-28 94 views
2

我試圖:如何將列的寬度調整爲CListCtrl中最長字符串的寬度?

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]); 
    } 

作爲柱的結果是寬度比上該列中的最大串的一個較大的20/30%。 我希望列的寬度將等於最大長度的字符串的寬度。

在此先感謝!

回答

3

這可能是因爲您沒有在設備上下文中選擇正確的字體。試試這個:

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]); 
    } 
+0

現在列的寬度比需要的小。 –

+0

您的列表控制所有者是否已繪製? –

+0

是的,繪製項目被執行 –

2

我認爲,所有你需要的是這樣的:

SetColumnWidth(col, LVSCW_AUTOSIZE); 

在我的項目,我得到我自己的類從CListCtrl和使用下面的函數

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); 
} 

這可以確保沒有內容列仍然根據標題文本獲得大小。

+0

不,我已經嘗試過在發佈我的問題之前,這沒有解決我的問題。 –

+0

@spin_eight - 真的嗎?這很奇怪 - 它適用於我 - 編輯我的答案以顯示我使用的代碼。 –

+0

我知道如何使用它,儘管感謝代碼。我與第三方課程一起工作,如果解決方案不適用。 –

相關問題