【问题标题】:Listbox width size dependent of text length列表框宽度大小取决于文本长度
【发布时间】:2009-12-13 04:10:37
【问题描述】:

我的应用程序有一个带有 ListBox 的窗口,其中填充了随时间变化的文本,因此 Listbox 条目可以有多个长度。

我想让窗口和列表框的宽度根据列表框条目的长度(字符数)动态变化。

例如,如果我的列表框有多个条目并且最大长度为 30 个字符,我想让窗口及其列表框的宽度大于一个最大长度为 20 个字符的窗口。

最好的方法是什么?

【问题讨论】:

    标签: mfc width clistbox


    【解决方案1】:

    试试这样的:

    // find the longest item
    CString longest;
    for (int i = 0; i < m_list.GetCount(); ++i)
    {
        CString temp;
        m_list.GetText(i, temp);
        if (temp.GetLength() > longest.GetLength())
            longest = temp;
    }
    
    // get the with of the longest item
    CSize size = GetWindowDC()->GetTextExtent(longest);
    
    // you need this to keep the current height
    RECT rect;
    m_list.GetWindowRect(&rect);
    
    // change only width
    int width = size.cx;
    int height = rect.bottom - rect.top;
    m_list.SetWindowPos(NULL, 0, 0, width, height, SWP_NOZORDER | SWP_NOMOVE);
    

    【讨论】:

    • 谢谢。这似乎是一个很好的解决方案。我一回到家就试试。
    • 您可能希望在每个字符串上调用 GetTextExtent。使用比例字体,短字符串完全有可能比长字符串宽。
    • 您需要确保使用列表框的设备上下文,即“m_list.GetWindowDC()”而不仅仅是“GetWindowDC()”。此外,要使用列表框的当前字体而不是默认系统字体来测量文本,您还需要“m_list.GetWindowDC().SelectObject(m_list.GetFont())”。
    【解决方案2】:

    您使用的是什么编程平台?我猜是 .NET 和 VB。

    放入一个方法来检查列表的内容并根据需要更改框和窗口的大小:

    Dim intMaxLength As Integer = 20
    For Each myItem As String In ListBox1.Items
        If Len(myItem) > intMaxLength Then  
           'Number of characters times number of pixels per character  
            ListBox1.Width = Len(myItem) * 10  
            'Me refers back to the form object  
            'Add a few extra pixels to give space around your listbox  
            Me.Width = Len(myItem) * 10 + 30  
        End If  
    Next  
    

    希望这能给你一个不错的起点。

    【讨论】:

    • 这改变了一切。我不是 C++ 人。也许其他人可以帮助你。 ;)
    【解决方案3】:

    试试这个:

    int maxcol = ((CHeaderCtrl*)(listctrl.GetDlgItem(0)))->GetItemCount()-1;
    for (int col = 0; col <= maxcol; col++)
    {
        listctrl.SetColumnWidth(col, LVSCW_AUTOSIZE_USEHEADER);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-14
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2017-07-28
      • 2020-11-14
      相关资源
      最近更新 更多