松鼠的博客

导航

统计

ListCtrl宽度自适应

Sample Image - AutosizeListCtrl.jpg

While creating a List Control using CListCtrl class, we need to specify the column width for all the columns in the very beginning, when we have little idea about the width required by the actual text that is going to come in the columns. So we leave it to the user to adjust the widths to see the entire text. This little enhancement over the CListCtrl class makes the column widths auto adjusting to keep the entire text of all the columns visible.

Make a new Dialog based application with MFC AppWizard (exe). Then add a new class to it (Insert -> New Class). Give any fancy name you wish (I chose CMyListCtrl) and in the base class dropdown, select CListCtrl. After clicking OK you have a CListCtrl derived class. Now add the following two public functions to this class:

 

Code

As we can see, this function calculates the widths of the Column Headers as well as the Items and sets the width to the larger of the two, so that complete header is visible even if no item is inserted. Also note that the last column will take all the remaining space.

To use our newly created class, first add a List Control to your dialog box (be sure to select 'Report' in the Styles page of the properties for the new control). Now, add a control variable for the newly created item (IDC_LIST1, or whatever ID you supplied) in the Member Variables page of the MFC Class Wizard (ctrl+W), but instead of accepting the default CListCtrl as the Variable type, select the new CMyListCtrl type. Call the variable m_myList. The wizard will suggest you to include the header file of your ListCtrl class in the dialog class. Do this by adding this line in the header file of your dialog class:
Code

After this, let’s insert some columns and rows to this ListCtrl. Add the following lines at the end of OnInitDialog() of your dialog class (or wherever you need):

Code
If it feels a little too involved to add the rows in a List Control, you can refer this article for a simpler way. Now, call the function AdjustColumnWidth() after inserting all rows.
Code

The call to this function makes sure all items and there headers are visible. You can play around with this example by putting different strings in the columns.

Enjoy :)

posted on   Xproer-松鼠  阅读(2288)  评论(1编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示