Search code examples
qt4qtreewidgetqtreewidgetitem

how to delete checked items from QTreeWidget?


I have list of QTreeWidget items with check boxes, which are child items with few top level items. I want to delete the items which are in checked state, how can I iterate the qtreewidget and delete those items ?


Solution

  • Easy. Not compiled, but hopefully you get the idea.

    for(int topnum = 0; topnum < treeWidget->topLevelItemCount(); ++topnum)
    {
        if(Qt::Checked == treeWidget->topLevelItem(topnum)->checkState(0))  //assume one column
        {
            delete treeWidget->takeTopLevelItem(topnum);
            --topnum;                       //decrement because you just removed it
        } else
        {
            QTreeWidgetItem* topitem = treeWidget->topLevelItem(topnum);
            for(int childnum = 0; childnum < topitem->childCount(); ++childnum)
            {
                if(Qt::Checked == topitem->child(childnum)->checkState())
                {
                    delete topitem->takeChild(childnum);
                    --childnum;
                }
            }
        }
    }
    

    Not sure I understand if the toplevel items are checked or if the children are checked, so I checked (haha) for both.