Search code examples
c++qtsearchwildcardqlineedit

Issue when searching QTableWidget using wildcards


In my Qt C++ application I have several items in a qtablewidget. A QLineEdit along with a button are used by me in order 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?


Solution

  • The == operator compare two strings and return true if they are exacly equals. If you want to use wildcards, I suggest to use QRegExp and use QRegExp::Wildcard as pattern syntax.

    Example 1:

    QString line = "aaaaLINEbbbb";
    QRegExp rx("*LINE*");
    rx.setPatternSyntax(QRegExp::Wildcard);
    rx.exactMatch(line); //should return true
    

    However, if you want to test only if a string contains a substring, I suggest to use bool QString::contains(const QString &str, Qt::CaseSensitivity cs) that can be faster.

    Example 2:

    QString line = "aaaaLINEbbbb";
    QString searchWord = "LINE";
    line.contains(searchWord); //should return true
    

    See: