PDA

View Full Version : Row index change when using QSortFilterProxyModel after sorting in QT4



quantity
28th February 2011, 03:50
Hi everybody,

I have a strange problem with QT's table model/view. I want to use subclass of QSortFilterProxyModel to implement sorting on a table. According to QT's reference, I do like this:


MyDataList list;
//initialize of list
MyTableModel* model = new MyTableModel(list);
MySortFilterProxyModel* proxyModel = new MySortFilterProxyModel;
proxyModel->setSourceModel(model);


The table view's sortingEnabled property is set to be true. When I click the horizontal header of the table, sorting behaves correctly except the row index is no longer starting from 1 and increase by 1. For example, before sorting, the row index is 1,2,3 from top to bottom, and after sorting, row index becomes 2,3,1. It seems row index is fixed to the row, which is not my expectation. What I want is the table behaves just like Microsoft Excel, row index does not change when sorting. Same problem occurs with filtering.

I didn't override any virtual function in MySortFilterProxyModel. If I don't use MySortFilterProxyModel and implement source model's sort() method, I can get the right behavior. I am not sure if it is a problem with QSortFilterProxyModel, or some mistake in my implementation. Any suggestion on this?

Thank you very much!

Lykurg
28th February 2011, 07:11
Then don't make the row index part of the data. Use the header e.g. QTableView::setVerticalHeader() of the view for that.

quantity
1st March 2011, 04:35
Then don't make the row index part of the data. Use the header e.g. QTableView::setVerticalHeader() of the view for that.

No, I didn't use any customized header widget, just the default vertical header of QTableView. Neither did I make row index part of model data. Everything here is defaulted. You can see the code I attached, building it in Qt Creator. Btw, I'm using QT 4.7.0.

Lykurg
1st March 2011, 08:41
Ok, then I had get you wrong. Sorry.

The Solution for your problem is pretty simple:
QVariant MySortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
return QSortFilterProxyModel::headerData(section, orientation, role);
return section + 1;
}

quantity
2nd March 2011, 10:03
Your solution just solves my problem. Thank you very much!

I wonder how operations perform when there's a proxy model attached to a source model. It seems that a method (virtual method declared in their parent) is first invoked in the proxy model. If we override the method and did not invoke its parent's one, corresponding method will not be invoked. Actually, it's the QSortFilterProxyModel::method() invokes the corresponding method in source model. Is it right?