0%

MFC表格:使用ListControl

  1. 设置表头、样式等
  2. 插入数据
  3. 选择

https://blog.csdn.net/qq_27290737/article/details/84980385

MFC CListCtrl Class

List样式参考

微软Windows桌面控件库

设置表头、样式等

设置样式:SetExtendedStyle,可以在列表初始化后对样式进行修改;ListCtrl还有另一种样式,只能在其创建时设置,例如通过资源视图的对话框控件属性设置,或者通过代码创建时用Create函数参数指定。其CreateEx函数可以同时设置两种样式:

1
2
3
4
5
6
virtual BOOL CreateEx(
DWORD dwExStyle,
DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd,
UINT nID);

dwExStyle 样式参考

dwStyle 样式参考

要让ListCtrl以表格的形式呈现,需要设置dwStyleLVS_REPORT,或者在资源视图中设置“外观”为“Report”。

插入表头使用InsertColumn函数。

使用示例:

1
2
3
4
5
6
7
8
9
10
11
// 设置样式
DWORD dwStyle = m_mfcEpsgList.GetExtendedStyle();
dwStyle |= LVS_EX_FULLROWSELECT; // 选中时整行选中
dwStyle |= LVS_EX_GRIDLINES; // 显示为网格线
m_mfcEpsgList.SetExtendedStyle(dwStyle);

// 根据控件宽度设置列宽
CRect listRect;
m_mfcEpsgList.GetWindowRect(listRect);
m_mfcEpsgList.InsertColumn(0, _T("空间参考系统"), LVCFMT_LEFT, listRect.Width() / 2);
m_mfcEpsgList.InsertColumn(1, _T("EPSG代码"), LVCFMT_LEFT, listRect.Width() / 2);

插入数据

插入一行: InsertItem

插入行之后就可以通过SetItemText设置该行不同列位置的文字

使用示例:

1
2
3
4
5
6
7
8
CString itemStr;
for (size_t i = 0; i < m_listEpsgCode.size(); i++)
{
itemStr = m_listEpsgName[i].c_str();
m_mfcEpsgList.InsertItem(i, itemStr);
itemStr = m_listEpsgCode[i].c_str();
m_mfcEpsgList.SetItemText(i, 1, itemStr);
}

选择

获取已选中的行号

1
int CListCtrl::GetSelectionMark() const

获取表格中的文字

1
CString GetItemText(_In_ int nItem, _In_ int nSubItem) const;

双击事件

1
ON_NOTIFY(NM_DBLCLK, IDC_DIALOG_List_SpatialRefSysSearch_SRSList, &CDlgEpsgSelectDlg::OnNMDblclkDialogListSpatialrefsyssearchSrslist)

双击事件响应函数的参数中获取行号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void CDlgEpsgSelectDlg::OnNMDblclkDialogListSpatialrefsyssearchSrslist(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
*pResult = 0;

NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
int r, c;
r = pNMListView->iItem; //每一行的item从零开始,双击选中行号
c = pNMListView->iSubItem; //每一行中的列就是SubItem也是从零开始,获得选中列号

if (r >= 0 && c >= 0)
{
SelectEpsgListItem(r);
}
}