QTreeWidget中的复选框使用

在树形结构中有时候需要在每项前添加复选框,能够进行勾选,复选框的添加可以使用tree本身的属性就行

 void QTreeWidgetItem::setCheckState ( int column, Qt::CheckState state )
Sets the item in the given column check state to be state.

 

添加完控件后,需要对树形结构的勾选操作做一些限定:

1、父项勾选后,子项自动全部勾选

2、子项部分勾选后,父项为部分选中状态

3、当子项全部勾选后,父项也会随之勾选

 

connect(tree,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(treeItemChanged(QTreeWidgetItem*,int)));

 

 1 void Count::treeItemChanged(QTreeWidgetItem *item, int column)
 2 {
 3     QString itemText = item->text(0);
 4     if (item->checkState(0) == Qt::Checked)
 5         {
 6         QTreeWidgetItem *parent = item->parent();
 7         int cnt = item->childCount();
 8         if (cnt >0)
 9             {
10             for (int i = 0;i < cnt;i++)
11                 {
12                  item->child(i)->setCheckState(0,Qt::Checked);
13             }
14         }
15         else
16             {
17             updateParentItem(item);
18         }
19     }
20     else if (item->checkState(0) == Qt::Unchecked)
21         {
22         int cnt = item->childCount();
23         if (cnt > 0)
24             {
25             for (int i = 0;i < cnt;i++)
26                 {
27                 item->child(i)->setCheckState(0,Qt::Unchecked);
28             }
29         }
30         else
31             {
32             updateParentItem(item);
33         }
34     }
35 }
36 void Count::updateParentItem(QTreeWidgetItem *item)
37 {
38     QTreeWidgetItem *parent = item->parent();
39     if (parent == NULL)
40     {
41        return;
42     }
43     //选中的子节点个数
44     int selectedCount = 0;
45     int childCount = parent->childCount();
46     for (int i = 0; i < childCount; i++)
47     {
48        QTreeWidgetItem *childItem = parent->child(i);
49        if (childItem->checkState(0) == Qt::Checked)
50        {
51         selectedCount++;
52        }
53     }
54     if (selectedCount <= 0)
55     {
56         //未选中状态
57        parent->setCheckState(0, Qt::Unchecked);
58     }
59     else if (selectedCount > 0 && selectedCount < childCount)
60     {
61        //部分选中状态
62        parent->setCheckState(0, Qt::PartiallyChecked);
63     }
64     else if (selectedCount == childCount)
65     {
66       //选中状态
67        parent->setCheckState(0, Qt::Checked);
68     }
69 }

 

posted on 2014-08-06 12:12  辉常的D调  阅读(10757)  评论(0编辑  收藏  举报

导航