displaying only part of model
-
Hi all -
I have a C++ model that is exposed to QML. I access the model in what I believe is in typical fashion:
GridView { model: zoneModel delegate: ZoneTile { titleText: model.name ...
There are places in my application where I'd like to exclude the first element in the list that the model returns.
First question: would it be preferable to accomplish this in the class that supports the model (say with a special function that slices the list), or in the QML? My sense is that the latter is preferable, but I can't figure out how to do it.
Making it invisible isn't enough, because it still takes up space. I could set its height and width to 0, and null out all its contents, but that seems kind of like a hack. Is there a better way to do this?
Thanks...
-
@mzimmers
I know nothing about QML. But if you have a source model and you want to alter it by, say, omitting the first row (element in list) it is trivially easy to do that by interposing aQAbstractProxyModel
between the source model and your QML/view. SubclassQIdentityProxyModel
(which passes through its source model unaltered) and have it (a) returnbase.rowCount() - 1
for itsrowCount()
override and (b) overridemapToSource()
/mapFromSource()
to add/subtract 1 to/from the row number. -
@JonB hey Jon - thanks for the suggestion. I've never really used proxy models before, but your suggestion prompted me to read a little more about them, and I can definitely see how they could also be useful in this situation.
I also decided, however, that what I'm trying to do is dumb, so I'm going to take a different approach. Basically I need to use the zones in the list as a filter for related items. I was trying to display them in a tab bar, but that's looking like a lousy idea, so I'm going to find a different way of displaying them.
Thanks for the suggestion, though; I'll be using it in the future.
-
-
And...the future is here!
class ZoneProxyModel : public QSortFilterProxyModel { Q_OBJECT public: explicit ZoneProxyModel(QObject *parent = nullptr); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override { bool rc = true; if (sourceRow == 0) rc = false; return rc; } };
Works perfectly. Thanks again, Jon.
-
@mzimmers hi,
You could even make it simpler:
class ZoneProxyModel : public QSortFilterProxyModel { Q_OBJECT public: explicit ZoneProxyModel(QObject *parent = nullptr); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override { Q_UNUSED(sourceParent); return sourceRow != 0; } };
-
@SGaist maybe it's because I'm old school, or maybe it's because I have enough trouble reading other people's code, but...whatever the reason, I prefer to explicitly derive a function's return value, assign it to a variable, and return that variable. I realize it accomplishes nothing, and in the absence of a good optimizing compiler, is actually fractionally slower, but...it's just how I roll.