c++ - 创建后无法更改 ListView 中的列宽

标签 c++ listview winapi

在将一些项目添加到 ListView 后,我需要使用 win32 api 更改列宽,因为垂直滚动条的宽度导致显示水平滚动条,我想将其删除。

但是 ListView_SetColumnWidth() 不会改变列的宽度。

//Column
int CreateColumn(HWND hwndLV, int iCol, char* Text, int iBreite)
{

LVCOLUMN lvc;

lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT ;
lvc.fmt=LVCFMT_LEFT;
lvc.cx = iBreite;
lvc.pszText =(LPWSTR)Text;  
lvc.iSubItem = iCol;

return ListView_InsertColumn(hwndLV, iCol, &lvc);
}

//item
int CreateItem(HWND hwndList, char*  Text)
{ 
 LVITEM lvi = {0};

 lvi.mask = LVIF_TEXT | LVCFMT_LEFT;
 lvi.pszText = (LPWSTR)Text;

 return ListView_InsertItem(hwndList, &lvi);
} 

 //Some code ...
 hwndList = CreateWindow(WC_LISTVIEW , L"" ,  WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL , 10 , 10 ,300 , 200, hwnd, NULL, GetModuleHandle(NULL), 0); 

 SendMessage(hwndList,LVM_SETEXTENDEDLISTVIEWSTYLE,LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT); 
 GetClientRect(hwndList , &rect);
 CreateColumn(hwndList , 0 , (char*)L"HEADER" , rect.right );

//Some other codes for adding items here

 ListView_SetColumnWidth(hwndList, 0,200); //Does not change the width

如何改变列的宽度?

最佳答案

对于初学者,您应该按如下方式更改两个“创建”函数(第二个与您的代码有很大不同):

//Column
int CreateColumn(HWND hwndLV, int iCol, const wchar_t* Text, int iBreite)
{
    LVCOLUMN lvc;
    lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; // You set iSubItem
    lvc.fmt = LVCFMT_LEFT;
    lvc.cx = iBreite;
    lvc.pszText = const_cast<wchar_t*>(Text);
    lvc.iSubItem = iCol;
    return ListView_InsertColumn(hwndLV, iCol, &lvc);
}

//item
int CreateItem(HWND hwndList, wchar_t* Text, int nItem) // Must have an item ID!
{
    LVITEM lvi; // Don't set to { 0, } as you immediately overwrite first item ...
    lvi.mask = LVIF_TEXT; // LVCFMT_LEFT is just plain wrong, here!
    lvi.pszText = Text;
    lvi.iItem = nItem;    // Must set this value;
    lvi.iSubItem = 0;
    return ListView_InsertItem(hwndList, &lvi);
}

您没有向我们展示添加项目的代码,但您需要为每个调用提供递增的 nItem 值。否则,您的项目将以相反的顺序显示!

我还假设您将非常量(即不是字符串文字)传递给 CreateItem。如果不是,则更改它,使其在处理 Text 的方式上类似于 CreateColumn

希望这对您有所帮助!

关于c++ - 创建后无法更改 ListView 中的列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728670/

相关文章:

android - 动态添加项目到listview android

c++ - 数字到固定长度的字符串

c++ - c++类中方法的实现

c++ - 是否有任何注册表项指示是否已安装特定的 C 运行时?

java - 在 ListView 中显示 POJO 对象的多个字段

android - 更新特定视频的媒体存储内容值

c++ - 在 C++\Win32(不是 MFC 或 CLI)中编写类似按钮的控件?

c# - 有没有办法为 Windows 窗体中的特定按钮 Hook 鼠标事件

c++ 如何在不进行深度复制的情况下展平 xtensor 的 View ?

c++ - 如何从其他线程停止 ReadDirectoryChangesW