【问题标题】:Unable to change column width in a listview after creating it创建列表视图后无法更改其列宽
【发布时间】:2019-08-30 14:29:27
【问题描述】:

在将一些项目添加到列表视图后,我需要使用 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

如何更改列的宽度?

【问题讨论】:

  • 为什么要将 Unicode const wchar_t[] 字符串类型转换为 char* 只是为了在 API 中将它们转换回 wchar_t*?完全摆脱 char 类型转换。将const wchar_t* 用于Text 参数,将const_cast<wchar*>(Text) 分配给Text 时使用pszText
  • ListView_SetColumnWidth 对我来说很好用。发布更多代码。你是如何创建 ListView 的?
  • @Anders 我添加了...我真的不明白为什么这不起作用...我要生气了
  • 你的字符串代码还是很奇怪,去掉所有(char*)(LPWSTR)演员表!仅使用const_cast<LPTSTR>(xyz)

标签: c++ listview winapi


【解决方案1】:

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

//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

希望这会有所帮助!

【讨论】:

  • @Zahra19977 但是,正如 Anders 在他的评论中所说,我尝试使用您的代码正如您发布的那样ListView_SetColumnWidth() 也适用于我。
  • 那么,你有什么来代替//Some other codes for adding items here ??
猜你喜欢
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多