Reputation: 547
I happen to have a ComboBox, and a QSortFilterProxyModel attached to it that orders the items alphabetically.
The Original model (QComboBox) is for example:
"C", "A", "D", "B"
The sorted model (QSortFilterProxyModel) becomes:
"A", "B", "C", "D"
If I now select "D" within the sorted comboBox, the signal QComboBox::currentIndexChanged(int) gives me index=3, but I would like to retrieve the index relative to the Original Model possibly, so index=2.
On the other hand I would also like to "Original Model"->setCurrentIndex(idx). But if if I define idx=2, in the comboBox the highlighted row shows "C", as the view is sorted.
How do I solve this?
Upvotes: 4
Views: 8573
Reputation: 98425
First, you need to obtain an index into the model displayed by the combo box. Use QAbstractItemModel::index
to do that. The "index" given by the combo box is the row.
To map from a proxy index to the source index, and from source index to the proxy index, use QSortFilterProxyModel::mapToSource
and mapFromSource
, respectively.
The view operates on the indices of the proxy, so any indices you get from the view must be mapped to the source model using mapToSource
. And vice-versa, if you operate on indices in the source model, and want to obtain the index on the view, use mapFromSource
.
E.g.:
connect(myComboBox, &QComboBox::currentIndexChanged, [=](int row){
auto proxy = static_cast<QAbstractProxyModel*>(myComboBox->model());
auto const proxyIndex = proxy->index(row, 0);
auto source = proxy->sourceModel();
auto const sourceIndex = proxy->mapToSource(proxyIndex);
...
});
Upvotes: 15