1. /**
    2. * @brief 查找与txt相同的item
    3. * @date 2020-11-10 10:56:33
    4. * @param txt 要查找的文本
    5. */
    6. void AddVistors::FindItem(const QString& txt)
    7. {
    8. ui->treeWidget->collapseAll();
    9. if (txt.isEmpty()) {
    10. QTreeWidgetItemIterator it(ui->treeWidget);
    11. while (*it) {
    12. (*it)->setForeground(0, Qt::black);
    13. it++;
    14. }
    15. return;
    16. }
    17. if (!ui->treeWidget->topLevelItemCount()) {
    18. return;
    19. }
    20. QTreeWidgetItemIterator it(ui->treeWidget);
    21. while (*it) {
    22. this->setCursor(Qt::WaitCursor);
    23. QString str = (*it)->text(0);
    24. if (-1 != str.indexOf(txt)) { // 精准匹配
    25. QTreeWidgetItem* pItem = (*it)->parent();
    26. if (pItem != nullptr) {
    27. bool isExpanded = pItem->isExpanded();
    28. if (!isExpanded) {
    29. ui->treeWidget->expandItem(pItem);
    30. }
    31. }
    32. (*it)->setForeground(0, Qt::red);
    33. ParentExpand(*it);
    34. } else {
    35. (*it)->setForeground(0, Qt::black);
    36. }
    37. it++;
    38. }
    39. this->setCursor(Qt::ArrowCursor);
    40. }
    41. /**
    42. * @brief 递归展开指定的节点的parent
    43. * @date 2020-11-10 10:58:27
    44. * @param item 树节点
    45. */
    46. void AddVistors::ParentExpand(QTreeWidgetItem* item)
    47. {
    48. if (item->parent() != nullptr) {
    49. QTreeWidgetItem* pItem = item->parent();
    50. if (!pItem->isExpanded()) {
    51. pItem->setExpanded(true);
    52. }
    53. ParentExpand(pItem);
    54. }
    55. }