PDA

View Full Version : Model/view, apply a filter on model



remy_david
4th February 2011, 10:17
Hello,

I am subclassing QSqlTableModel for a model used by a QListView.
This model represents data stored in a SQLite database.
In this database I have a flag field (let say an int field at column 0).
I want my model to present data depending on the flag value, in other word I want to apply a filter on my model.
So I have a public method setFilter(int flag) to set the current filter on flag value, and I want my model to present only the data (rows) that match this value.

Let say my db is like:


flag | value
0 | foo
1 | bar


After setFilter(0) I want my model to present only:


flag | value
0 | foo


The code :


MyModel::MyModel(QObject *parent) :
QSqlTableModel(parent),
{
setTable("myTable");
select();
}

void
MyModel::setFilter(int flag)
{
currentFlag = flag; // currentFlag is MyModel class member
}

QVariant
MyModel::data(const QModelIndex & index, int role ) const
{
if( index.model()->data(index.sibling(index.row(),0)) == currentFlag) // if the current index points to a row with flag column equals to the current filter, return the value, but this leads to infinite recursive call
return QSqlTableModel::data(index, role);
else return QVariant(); // else return an invalid data
}


Problem is, to check the flag value I have to call data() inside the data() method, which leads to infinite recursive call.
How can I solve this ? How can I check value of another ModelIndex in the QAbstractItemModel::data() method ? Is it possible or am I using Model/view classes the wrong way ?

Hope everything is clear.

Ginsengelf
4th February 2011, 10:38
Hi, you can try a proxy model (like QSortfilterProxyModel). The proxy model will check the flag, the normal model underneath will provide the data.

Ginsengelf

mcosta
4th February 2011, 10:43
Use QSqlTableModel::setFilter().

For example



void
MyModel::setFilter(int flag)
{
QString filterString (QString ("flag=%1").arg(flag));
this->setFilter (filterString);
select();
}

remy_david
4th February 2011, 14:16
Thanks ! both work !

mcosta
4th February 2011, 17:13
The solution of Ginsengelf it's good and it's more general than mine.

When you use an HUGE Database, probably, my solution is faster because the sorting/filtering phase it's optimized in SQL engines.