PDA

View Full Version : How to check/uncheck all the items in a QTreeWidget?



qlands
5th March 2010, 09:22
Hi,

I'm using QT Creator to develop an small application. I have a QTreeWidget in the UI and I use the following code to populated:



QTreeWidgetItem *mainhh = new QTreeWidgetItem(this->ui->treetables);
mainhh->setText(0, tr("Main Table"));
QStringList lista;
//Move the items to the list
lista << tr("Sub-table 1");
lista << tr("Sub-table 2");
lista << tr("Sub-table 3");
//Many more items ........
//Add the list of subtables as a children of Main Table
new QTreeWidgetItem(mainhh,lista,0);
//Many more parent nodes and childs.......
this->ui->treetables->expandAll(); //Expand the tree


The code works fine but how can I check/uncheck all the items after I have fulled populated the tree e.g., by clicking a button called "Check/Uncheck all". I guess I need to set some flags and properties to each items with something like:


setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
setCheckState(Qt::Unchecked); //or QT::Checked


But.... I don't know how to go through all the items in the tree to set those properties and flags to each item.

Many thanks,
QLands

wysota
5th March 2010, 10:57
Can't you do it while populating the tree?

qlands
5th March 2010, 11:41
Well... Yes I can but I still need to implement a "Check/Uncheck all" button. And for this I would like to use a FOR statement. For example, if I use a QListWidget is can implement the code really easy with:


for (pos =0; pos <= this->ui->lsttables->count()-1; pos++)
{
this->ui->lsttables->item(pos)->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
this->ui->lsttables->item(pos)->setCheckState(Qt::Unchecked);
}


But, with a QTreeWidget, I have no clue how to do it.

Thanks.

wysota
5th March 2010, 11:48
void checkSubTree(QTreeWidgetItem *item, Qt::CheckState st){
item->setCheckState(0, st);
for(int i=0;i<item->childCount();i++)
checkSubTree(item->child(i), st);
}

for(int i=0;i<tree->topLevelItemCount();i++){
checkSubTree(tree->topLevelItem(i), Qt::Checked);
}

Be warned it might be very slow for many items. A model-based approach should be much faster (apart when using QStandardItemModel).

qlands
5th March 2010, 13:21
Brilliant...

Thanks a lot.

jialrs
7th July 2010, 04:58
maybe you can use a QList<QTreeWidgetItem *> to store all the point of all the item object , and just use a for loop to check/uncheck , this will be more faster and just use a little of memory .....