一直以来duilib并没有Grid,大多还是使用CListUI做数据表格,或者有些人像我一样,把CGridCtrl(也就是MFCGridCtrl)这个开源库拉进来用。只是CGirdCtrl有个不好的是它继承自CWnd类,是个MFC类,为此,特意开发CGridListUI,作为数据表格,同时为了以后在项目中替代CGridCtrl。
CGridListUI主要是结合CListUI和CGridCtrl,我的目标是替代CGridCtrl,所以函数调用等格式尽量兼容CGridCtrl。
每个单元格都是一个容器,也就是每个格子差不多要占用2K内容,想想就知道了,数据量大时,只能使用虚表。
表格内置了几种单元格类型:分别是文本,编辑框,复选框,下拉框,时间选取,容器。
typedef enum enumGridListCellType
{
celltypeText = 0,
celltypeEdit = 1,
celltypeCheckBox = 2,
celltypeCombo = 3,
celltypeDateTime = 4,
celltypeDate = 5,
celltypeTime = 6,
celltypeContainer = 7
}GridListCellType;
实表的填充
//表格填充
m_pGrid->SetRowCount(12);
for (int i=0; i<m_pGrid->GetRowCount(); i++)
{
for (int j=1; j<m_pGrid->GetColumnCount(); j++)
{
CString temp;
temp.Format(_T("%02d,%02d"), i, j);
m_pGrid->Cell(i,j).SetText(temp);
}
}
//插入单行
int row = m_pGrid->InsertRow();
for (int j=1; j<m_pGrid->GetColumnCount(); j++)
{
CString temp;
temp.Format(_T("%02d,%02d"), row, j);
m_pGrid->Cell(row,j).SetText(temp);
}
虚表的填充,程序接收DUI_MSGTYPE_DRAWITEM消息。
void CMainFrame::OnNotifyDrawItem(TNotifyUI& msg)
{
if(IsControl(msg, _T("grid_main")))
{
int lo = msg.wParam; //需要更新的开始行
int hi = msg.lParam; //需要更新的结束行
//InsertMsgUiV(_T("DrawRange=%d,%d"), lo, hi);
//获取排序列和排序顺序
int sort_col = m_pGrid->GetSortColumn();
BOOL bAscending = m_pGrid->GetSortAscending();
//填充表格内容
for (int i=lo; i<=hi; i++)
{
for (int j=1; j<m_pGrid->GetColumnCount(); j++)
{
if(sort_col > 0 && !bAscending)
{
CDuiString s;
s.Format(_T("%d,%d"), m_pGrid->GetRowCount()-i, j);
m_pGrid->Cell(i,j).SetText(s);
}
else
{
CDuiString s;
s.Format(_T("%d,%d"), i, j);
m_pGrid->Cell(i,j).SetText(s);
}
}
}
}
}
点击表格头进行排序时,程序接收到DUI_MSGTYPE_SORTITEM消息。
void CMainFrame::OnNotifySortItem(TNotifyUI& msg)
{
if(IsControl(msg, _T("grid_main")))
{
//如果是虚表,当收到这个消息时,需要对本地数据进行排序,比如数据库查询,要改一下select末尾那个order by。同时调用ResetVirtualOrder(), 这个函数会强制触发DUI_MSGTYPE_DRAWITEM,进行刷新表格。
if(m_pGrid->IsVirtualGrid())
{
m_pGrid->ResetVirtualOrder();
}
}
}
这个类可能不是太完善,还有BUG,欢迎提出你的建议,详情请看代码。
代码共享地址:
https://gitee.com/Liqs99/DuiLib_DuiEditor
https://github.com/xfcanyue/DuiLib_DuiEditor
duilib设计器交流群:819272442