3

简要说明:
我得到了一个CTreectrl存储对象的类的实例,当对象选择对象的对象列表报告显示为该对象。
我需要调整派生自的 MyListCtrl 类实例的列的宽度,CListCtrl以便用户可以在不调整列大小的情况下看到该列中的数据。

我如何处理我的任务:
我实现了从树中选择对象时调用的方法 InitColumnWidth

    void COwnListCtrl::InitColumnWidth ( unsigned const * defwidth, BOOL chars )
        {
            /* find the largest string in each column and set column width accordingly
            so that user no longer need to manually adjust columns width */

            RECT r;
            GetClientRect ( & r );
            int* arrOfMaxColumnWidth = new int[NumCol]; // array where max length for columns will be stored
            for (int i = 0; i < NumCol; ++i)
                arrOfMaxColumnWidth[i] = 0; // initialize
            tstring dataInColumn;
            double Scale = ( defwidth && chars ) ? GetCharAveWidth ( * GetFont () ) : ( r.right * 0.01 );
            int numberOfVisitedItems = 0;
            do
            {
                dataInColumn = _T(""); // initialize
                for (int col = 0; col < NumCol; ++col)
                {
                    //DWORD const itemData = this->GetItemData(numberOfVisitedItems);

                    dataInColumn = this->GetSubItemString(this->GetItemData(numberOfVisitedItems), col); 
                /* 1-st varaint returns only first row of the list 
           because GetItemData always returns zero, but I need to visit all rows */
                    dataInColumn = this->GetSubItemString(numberOfVisitedItems, col); 
   /* 2-nd variant, works for most objects from CTreeCtrl, but for a few of them assertion is raised, system reports on the corrupted heap and application terminates*/
                    if (dataInColumn.length() > arrOfMaxColumnWidth[col])
                        arrOfMaxColumnWidth[col] = dataInColumn.length();
                }
                ++numberOfVisitedItems;
            }
            while(dataInColumn.length() != 0); /* do{} while loop is used to get number of rows in the table
                                       as long as an empty string is read, which means that all rows were read*/
            for (int col = 0; col < NumCol; ++col)
                int tmp = ColWidth[col] = arrOfMaxColumnWidth[col] * Scale;
            ColWidth[0] = 100;

需要帮忙!

4

2 回答 2

4

使用它(用for (int col = 0; col < NumCol; ++col)下面的代码替换你的):

for (int col = 0; col < NumCol; ++col)
{
    int len = 0;
    for(int row = 0; this->GetItemCount(); ++row)
    {
        CString item = this->GetItemText(row, col);
        if(item.GetLength() > len) len = item.GetLength();
    }
    if (len > arrOfMaxColumnWidth[col])
        arrOfMaxColumnWidth[col] = len; // should you multiple it to Scale?
}
于 2013-04-24T01:39:20.577 回答
1

No need to reinvent the wheel. If you just want to resize the columns to fit the text try:

for (int i = 0; i < NumCol; ++i)
    ListView_SetColumnWidth( m_hWnd, i, LVSCW_AUTOSIZE );
于 2013-10-30T14:27:26.380 回答