Model/view, apply a filter on model
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:
Quote:
flag | value
0 | foo
1 | bar
After setFilter(0) I want my model to present only:
Quote:
flag | value
0 | foo
The code :
Code:
MyModel
::MyModel(QObject *parent
) :{
setTable("myTable");
select();
}
void
MyModel::setFilter(int flag)
{
currentFlag = flag; // currentFlag is MyModel class member
}
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
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.
Re: Model/view, apply a filter on model
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
Re: Model/view, apply a filter on model
Use QSqlTableModel::setFilter().
For example
Code:
void
MyModel::setFilter(int flag)
{
this->setFilter (filterString);
select();
}
Re: Model/view, apply a filter on model
Re: Model/view, apply a filter on model
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.