[SOLVED] QSortFilterProxyModel::mapFromSource crashes application



  • I have a view (QTableView), proxy model used for sorting (QSortFilterProxyModel), and the model proper (QSqlTableModel). I am trying to save row selection (selection of individual cells is disabled) in the view and restore it, if possible, after a database update (when model->select() is called). The selection is stored as a list of model row numbers (integers) in the following way:

    @selection.clear();
    foreach (QModelIndex idx, view->selectionModel()->selectedRows())
    selection << proxy->mapToSource(idx).row();@

    The resulting list is correct, it is filled with the original model row numbers independent of the current sorting by QSortFilterProxyModel.

    However, when I try to restore the selection in the following way:

    @if (!selection.isEmpty())
    {
    view->setSelectionMode(QAbstractItemView::MultiSelection);
    foreach (int i, selection)
    {
    if (i >= 0 && i < view->model()->rowCount())
    {
    QModelIndex idx = proxy->index(i, 0);
    int row = proxy->mapFromSource(idx).row();
    view->selectRow(row);
    }
    }
    }@

    The program crashes when calling proxy->mapFromSource(idx).row(). What am I doing wrong? The following code works:

    @if (!selection.isEmpty())
    {
    view->setSelectionMode(QAbstractItemView::MultiSelection);
    foreach (int i, selection)
    {
    if (i >= 0 && i < view->model()->rowCount())
    view->selectRow(i);
    }
    }@

    Of course, in this case the restored selection corresponds to the original model row numbers, not to row numbers after sorting.


  • Lifetime Qt Champion

    Hi,

    Might be a silly question, but is the proxy correctly instantiated before calling mapFromSource ?



  • It is. The view, the proxy, and the model are all instantiated only once, in the constructor of the widget containing the view. There are no issues with presenting and sorting the table model, so the proxy works properly. Moreover, the first piece of code, where proxy->mapToSource is called, is always executed before the second piece (with mapFromSource call). And

    @QModelIndex idx = proxy->index(i, 0);@

    line, just before mapFromSource call, produces a QModelIndex object which looks correct (in the debugger).


  • Lifetime Qt Champion

    Ok, I see. I think the problem is that you are trying to use mapFromSource with an index coming from the proxy model.

    mapFromSource should be called with an index from the source model.



  • Thank you, you are absolutely right! Changing the line

    @QModelIndex idx = proxy->index(i, 0);@

    to

    @QModelIndex idx = model->index(i, 0);@

    solved the problem.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.