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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With