Qt中搜索框输入不同字符串显示列表的内容改变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void FixedWingAircraftModelManager::slotBackgroundFilter(QString f){ // 根据lineEdit框内文字,动态刷新item列表显示
const bool empty = f.isEmpty();
QRegExp re = empty ? QRegExp() : QRegExp(f,Qt::CaseInsensitive,QRegExp::FixedString);

const int numTopLevels = ui->treeWidget->topLevelItemCount();
for(int i = 0; i< numTopLevels; i++ ){
QTreeWidgetItem *ti = ui->treeWidget->topLevelItem(i);
setBackgroundFilter(ti,re);
}
}

int setTreeItemHidden(QTreeWidgetItem* item){
if(item->childCount() != 0){
for(int i = 0; i < item->childCount(); i++){
item->child(i)->setHidden(false);
setTreeItemHidden(item->child(i));
}
}
return 0;
}

int setBackgroundFilter(QTreeWidgetItem *item,QRegExp re){
if(item == NULL) return 0;
int nVisibleCount = 0;
int count = item->childCount();

QString text = item->text(0);
bool bMatched = text.contains(re);
if(bMatched){
item->setHidden(false);
setTreeItemHidden(item);
return count;
}else{
for(int i = 0; i< count; i++){
QTreeWidgetItem* child = item->child(i);
setBackgroundFilter(child,re);
if(!child->isHidden()){
nVisibleCount ++;
}
}
}
item->setHidden(nVisibleCount == 0);
return nVisibleCount;
}