Search code examples
c++qtqtableviewqsqlqueryqsortfilterproxymodel

QTableView does not update the data


I'm using a QTableView to view some data from sql database. the structure is as follows :

  1. QSqlQueryModel
  2. subclass of QSortFilterProxyModel that's used to filter data through search box
  3. QTableView and it's model is the proxy model.

Sometimes when I search and the FilterAcceptsRow is called, the view doesn't load the data, surprisingly when I resize the window or click on the header to sort it, the data gets loaded !

bool ProxyModel::filterAcceptsRow(int source_row,
                                  const QModelIndex &source_parent) const
{
    QModelIndex indName = sourceModel()->index(source_row,
                                               7, source_parent);
    QModelIndex indNumber= sourceModel()->index(source_row,
                                               6, source_parent);
    QModelIndex indAgency = sourceModel()->index(source_row,
                                               0, source_parent);

    QModelIndex indStartDate = sourceModel()->index(source_row,2,source_parent);
    QModelIndex indEndDate = sourceModel()->index(source_row,1,source_parent);
    if (searchBy == 0) // search by name
    {
        if(sourceModel()->data(indName).toString().contains(name_))
            return true;
        else
            return false;
    }
    else if( searchBy == 1)  // search by number
    {
        if(sourceModel()->data(indNumber).toString().toLower().contains(number_.toLower()))
            return true;
        else
            return false;
    }
    else if (searchBy == 2) // search by agency
    {
        return agencyList.indexOf(sourceModel()->data(indAgency).toString()) == agency_ ;
    }

    else if (searchBy == 3) // search By date
    {
        if (sourceModel()->data(indStartDate).toDate() >= start_ &&
               sourceModel()->data(indEndDate).toDate() <= end_)
        return true;
    }

    return false;
}

Is there someway to get this working properly ?


Solution

  • I found the fix for that issue, It turns out that the QSortFilterProxyModel does not load all the data until you scroll the QTableView down, then it starts to load the rest of the data. and that might be a good thing if there is a lot of data, so it's on by default.

    I got it working the way i needed by using

    bool QAbstractItemModel::canFetchMore(const QModelIndex &parent) const
    

    and

    void QAbstractItemModel::fetchMore(const QModelIndex &parent)
    

    after each call for invalidateFilter();

    I call them to fetch all the data

    while (canFetchMore(sourceModel()->index(rowCount()-1,0)))
    {
        fetchMore(sourceModel()->index(rowCount()-1,0));
    }