PDA

View Full Version : Searching with QRefExp, Wildcards



deepal_de
6th June 2011, 14:41
Hello

i have a QTableWidget and a QlistWidget..
im implementing a search function like i Qt Designer.
When the user types something in the textbox items in QTableWidget and QlistWidget will be filtered..

how can i add wildcard searching functionality to my search function...
can someone post a code sample

thanks..

Lykurg
6th June 2011, 14:42
maybe you could first post your code you are using. Using wildcards is just a parameter for your QRegExp.

deepal_de
7th June 2011, 05:33
sorry for taking a long time to reply :)

I have something like this

.cpp


#include "mainwindow.h"
#include "ui_mainwindow.h"

QStringList lst_ListItems;
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);

lst_ListItems.append("QtBlog");
lst_ListItems.append("QtCenter");
lst_ListItems.append("QtCreator");
lst_ListItems.append("QtDesigner");
lst_ListItems.append("Wildcard");

for(int iIndex = 0; iIndex < lst_ListItems.count(); ++iIndex)
{
QListWidgetItem* pItem = new QListWidgetItem;
pItem->setText(lst_ListItems.at(iIndex));
ui->lstNamesControl->addItem(pItem);// lstNamesControl is a QListWidget
}
}

MainWindow::~MainWindow()
{
delete ui;
}


void MainWindow::on_txtSearch_textChanged(QString )
{
QString sSearch = ui->txtSearch->text(); // txtSearch is a QLineEdit
ui->lstNamesControl->clear();
for(int iIndex = 0; iIndex < lst_ListItems.count(); ++iIndex)
{
QListWidgetItem* pItem = new QListWidgetItem;
pItem->setText(lst_ListItems.at(iIndex));
if(pItem->text().contains(sSearch, Qt::CaseInsensitive))
ui->lstNamesControl->addItem(pItem);
}
}



How can i add WildCards to something like this??

Lykurg
7th June 2011, 09:50
Hi, a more sophisticated way to filter a list would be to use a QSortFilterProxyModel with QStringListModel and QListView. But with your code: First the slot receives ui->txtSearch->text() as a parameter, so there is no need to query it again. Inside the loop do something have a look at: QRegExp in general and specific QRegExp::exactMatch(), QRegExp::setPatternSyntax() with QRegExp::Wildcard.

deepal_de
7th June 2011, 10:14
can you please post a example code...

i used it like this,but its not working


QString sSearch = ui->txtSearch->text();
ui->lstNamesControl->clear();

QRegExp regExp;
regExp.setPatternSyntax(QRegExp::Wildcard);
for(int iIndex = 0; iIndex < lst_ListItems.count(); ++iIndex)
{
QListWidgetItem* pItem = new QListWidgetItem;
pItem->setText(lst_ListItems.at(iIndex));
if(regExp.exactMatch(pItem->text()))
ui->lstNamesControl->addItem(pItem);


Added after 8 minutes:

ohh. my mistake... got it :)
Thanks Lykurg


QRegExp regExp(sSearch );