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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM