Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item of the source model from the index of a QSortFilterProxyModel

Tags:

qt

I have an application that contains a QTreeView whose underlying model, say MyModel is derived from a QStandardItemModel. In order to filter out from the view some of the items of MyModel, I plug it into a QSortFilterProxyModel which is in turn plugged into the QTreeView. When I need to get one item of my source model from a given index of my proxy model I always have to code this:

auto my_model = dynamic_cast<MyModel*>(proxy_model->sourceModel());
auto source_index = proxy_model->mapToSource(proxy_index);
auto item = my_model->itemFromIndex(source_index);

I did not find any direct method to do this. Would you be aware of more direct way to do this or is that the sign that I imserunderstand something in the way I use Qt proxy model concept ?

like image 333
Eurydice Avatar asked Jun 12 '18 08:06

Eurydice


1 Answers

You are using it correctly - there is no built in shortcut for the steps you are doing.

You could use qobject_cast to speed things up if MyModel has the Q_OBJECT macro, but otherwise thats exactly how to use the models.

For situation like these, I typically create a wrapper method on the class that is using the models or extend the QSortFilterProxyModel to have such a method. YOu could, for example create a StandardSortFilterProxyModel that extends the former and only accepts QStandardItemModel based classes and provides a bunch of methods to access the items the way you need to.

Note that if you only want to get specific data out of the model instead of the item itself (like the text of the selected column), you can always use proxy_model->data(proxy_index) directly and get your value from the QVariant.

like image 124
Felix Avatar answered Oct 26 '22 09:10

Felix