首页 > 代码库 > Qt树形列表复选框操作
Qt树形列表复选框操作
Qt树形列表复选框操作
void CCheckBoxDialog::treeItemsChangeStol(QTreeWidgetItem *pCurrentItem, int)
{
if (m_itemsCount <= 0)//没有子节点,不存在选中操作
{
updateComboInfoStol();
return;
}
if (Qt::Checked == pCurrentItem->checkState(0))
{
//QTreeWidgetItem *parentItem = pCurrentItem->parent();
int childCount = pCurrentItem->childCount();
if (childCount >0)//父节点被选中
{
for (int i=0; i<childCount; i++)
{
pCurrentItem->child(i)->setCheckState(0, Qt::Checked);
}
}
else //更新父节点复选框状态
{
updateParentItemStateStol(pCurrentItem);
}
}
else if (Qt::Unchecked == pCurrentItem->checkState(0))
{
//QTreeWidgetItem *parentItem = pCurrentItem->parent();
int childCount = pCurrentItem->childCount();
if (childCount >0)//父节点被选中
{
for (int i=0; i<childCount; i++)
{
pCurrentItem->child(i)->setCheckState(0, Qt::Unchecked);
}
}
else //更新父节点复选框状态
{
updateParentItemStateStol(pCurrentItem);
}
}
updateComboInfoStol();
}
void CCheckBoxDialog::updateParentItemStateStol(QTreeWidgetItem *pCurrentItem)
{
QTreeWidgetItem *parentItem = pCurrentItem->parent();
if (parentItem == NULL)
{
return;
}
int selectedCount = 0;//当前子节点选中个数
int childCount = parentItem->childCount();
for (int i=0; i<childCount; i++)
{
QTreeWidgetItem *childItem = parentItem->child(i);
if (Qt::Checked == childItem->checkState(0))
{
selectedCount++;
}
}
if (selectedCount <= 0)
{
//未选中任何项
parentItem->setCheckState(0, Qt::Unchecked);
}
else if (selectedCount>0 && selectedCount<childCount)
{
//选中部分子项
parentItem->setCheckState(0, Qt::PartiallyChecked);
}
else if (selectedCount == childCount)
{
//选中所有子项
parentItem->setCheckState(0, Qt::Checked);
}
}
Qt树形列表复选框操作