Searching a QTable widget items using wild cards!
-
IN my qt c++ application I have several items in a qtablewidget. A lineedit along with a button is used by me inorder to search the qtablewidget when a particular word is given to the line edit and the search button is clicked! FOllowing is my code!
bool found=false; QString Line= ui->search->text(); for(int i=0;i<100;i++){ if(ui->tableWidget->item(i,0)->text()== Line){ found = true; break; } } if(found){ ui->tableWidget->clear(); ui->tableWidget->setItem(0,0,new QTableWidgetItem(Line)); } else{ QMessageBox::warning(this, tr("Application Name"), tr("The word you are searching does not exist!") ); }This code works if an exact word in the table widget is given but if I use
ui->tableWidget->item(i,0)->text()=="%"+ Line+"%"
it won't work for the wild card scenario so that I can search even part of a word is given! How can I correct this issue?
-
IN my qt c++ application I have several items in a qtablewidget. A lineedit along with a button is used by me inorder to search the qtablewidget when a particular word is given to the line edit and the search button is clicked! FOllowing is my code!
bool found=false; QString Line= ui->search->text(); for(int i=0;i<100;i++){ if(ui->tableWidget->item(i,0)->text()== Line){ found = true; break; } } if(found){ ui->tableWidget->clear(); ui->tableWidget->setItem(0,0,new QTableWidgetItem(Line)); } else{ QMessageBox::warning(this, tr("Application Name"), tr("The word you are searching does not exist!") ); }This code works if an exact word in the table widget is given but if I use
ui->tableWidget->item(i,0)->text()=="%"+ Line+"%"
it won't work for the wild card scenario so that I can search even part of a word is given! How can I correct this issue?
You can use
QAbstractItemModelto solve the problem easily.like this:
#include <QAbstractItemModel> #include <QModelIndexList> [...] auto model = ui->tableWidget->model(); auto items = model->match( model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(QString("*%1*").arg(Line)), 1, // -1: for all matching items Qt::MatchWildcard); if (!items.isEmpty()) { ui->tableWidget->clear(); ui->tableWidget->setItem(0,0,new QTableWidgetItem(Line)); } [...] -
- separate
QTableWidgetinto aQTableViewand aQStandardItemModel - add a
QSortFilterProxyModelas the model ofQTableViewand set theQStandardItemModelas theQSortFilterProxyModel'ssourceModel - call
QSortFilterProxyModel::setFilterWildcardorQSortFilterProxyModel::setFilterRegExpto perform the searching
- separate