Important: Please read the Qt Code of Conduct -

Search in a subtree of QTreeWidget

  • In QTreeWidget there is a function called findItems to find items in the tree with a specific value. However, I want to search in a subtree of the QTreeWidget. I have a pointer to the topnode of the subtree (a QTreeWidgetItem). To search in the tree I have so far thought about making a new tree which only consists of the subtree and use the findItems function, but I don't know how to this. addTopLevelItem doesn't seem to work for this. Is there an easy way to do this? Is there a better way to search in a subtree?

  • You could just write your own search function that recurses down into only the provided sub-tree.

  • @
    QTreeWidgetItem * cur_item = ui->treeWidget->currentItem();
    QTreeWidgetItem * base_item = cur_item;
    while(base_item->parent() != 0)
    base_item = base_item->parent();

    int id_of_cur_top_level = ui->treeWidget->indexOfTopLevelItem(base_item);

    QList<QTreeWidgetItem*> list = ui->treeWidget->findItems("My item", Qt::MatchExactly | Qt::MatchRecursive, 0);

    QTreeWidgetItem* searched_item = 0;

    for(QList<QTreeWidgetItem*>::iterator it = list.begin();it != list.end(); ++it){
    base_item = *it;

    while(base_item->parent() != 0)
    base_item = base_item->parent();

    int i = ui->treeWidget->indexOfTopLevelItem(base_item);

    if(i == id_of_cur_top_level){
    searched_item = *it;

    if(searched_item != 0){
    // todo

Log in to reply