QTreeWidgetItems search issue



  • Hi! I want to search items in QTreeWidget. The problem is, it doesn't hide the items that don't match the string.

    QString data = "Some text";
    QList<QTreeWidgetItem*> itemsList = treeWidget->findItems(data, Qt::MatchContains | Qt::MatchRecursive, 0);
        for (QTreeWidgetItem *item : itemsList)
        {
            if (!data.isEmpty()) {
                if (item->text(0) == data) {
                    item->setHidden(false);
                } else {
                    item->setHidden(true);
                }
            } else {
                item->setHidden(false);
            }
        }
    

    I want to hide items when they are not matching, and display the matching one. Thanks.


  • Lifetime Qt Champion

    Hi,

    You are only looping on items that do match your search so the others will stay untouched.



  • @SGaist

    Ok. Thanks. I will fix it later and reply.



  • @SGaist

    Thank you. I have fixed the issue. I post code here, so people can find a solution.

    Code:

    for (int i = 0; i < treeWidget->topLevelItemCount(); i++) {
            QTreeWidgetItem *item = treeWidget->topLevelItem(i);
            QList<QTreeWidgetItem*> itemsList = treeWidget->findItems(data, Qt::MatchContains | Qt::MatchRecursive, 0);
            for (QTreeWidgetItem *searchedItem : itemsList)
            {
                if (!data.isEmpty()) {
                    searchedItem->setHidden(false);
                    item->setHidden(true);
                } else {
                    item->setHidden(false);
                }
            }
        }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.