Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QSortFilterProxyModel: retrieve the item or index of the original model

Tags:

qt

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?

like image 948
TakeMeToTheMoon Avatar asked Oct 30 '25 07:10

TakeMeToTheMoon


1 Answers

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);
  ...
});
like image 89
Kuba hasn't forgotten Monica Avatar answered Oct 31 '25 20:10

Kuba hasn't forgotten Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!