Qt 基础
```cpp
QTreeWidgetItem *subitem22 = new QTreeWidgetItem(group2);
subitem22->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
subitem22->setText(0, "subitem22");
subitem22->setCheckState(0, Qt::Unchecked);
QTreeWidgetItem *subitem23 = new QTreeWidgetItem(group2);
subitem23->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
subitem23->setText(0, "subitem23");
subitem23->setCheckState(0, Qt::Unchecked);
void Widget::treeitemChanged(QTreeWidgetItem* item, int column)
{
QString itemText = item->text(0);
// 选中时
if (Qt::Checked == item->checkState(0))
{
QTreeWidgetItem* parent = item->parent();
int count = item->childCount();
if (count > 0)
{
for (int i = 0; i < count; i++)
{
// 子节点也选中
item->child(i)->setCheckState(0, Qt::Checked);
}
}
else
{
// 是子节点
updateParentItem(item);
}
}
else if (Qt::Unchecked == item->checkState(0))
{
int count = item->childCount();
if (count > 0)
{
for (int i = 0; i < count; i++)
{
item->child(i)->setCheckState(0, Qt::Unchecked);
}
}
else
{
updateParentItem(item);
}
}
}
Qt5 模板库、工具类及控件
```cpp
void Widget::updateParentItem(QTreeWidgetItem* item)
{
QTreeWidgetItem *parent = item->parent();
if (parent == NULL)
{
return;
}
// 选中的子节点个数
int selectedCount = 0;
int childCount = parent->childCount();
for (int i = 0; i < childCount; i++)
{
QTreeWidgetItem *childItem = parent->child(i);
if (childItem->checkState(0) == Qt::Checked)
{
selectedCount++;
}
}
if (selectedCount <= 0)
{
// 未选中状态
parent->setCheckState(0, Qt::Unchecked);
}
else if (selectedCount > 0 && selectedCount < childCount)
{
// 部分选中状态
parent->setCheckState(0, Qt::PartiallyChecked);
}
else if (selectedCount == childCount)
{
// 全部选中状态
parent->setCheckState(0, Qt::Checked);
}
}
```
请注意,以上代码是对您提供的内容进行整理后的部分代码示例,并不具备可编译性。您可以根据这些示例结合您的项目需求进行适当的修改和使用。