Skip to content

KDFunctionalSortFilterProxyModel A Functional Sort/Filter Proxy Model

Another day, another small addition to KDToolBox, KDAB’s collection of miscellaneous useful C++ classes and stuff.

In this post, we’re going to talk about KDFunctionalSortFilterProxyModel, which is a convenience subclass of QSortFilterProxyModel.

What’s a proxy model to begin with, and what’s QSortFilterProxyModel? Well, that explanation requires a bigger space than what I have in this blog post. I’ll leave that one to Jesper:

Most of the time, QSortFilterProxyModel works just fine “out-of-the-box,” at least when it comes to sorting. But when it comes to filtering, we typically have to subclass it in order to override its row-accept and/or column-accept functions. This is easy, but in a project that makes extensive use of proxy filters, it’s also quite annoying that every time we need a different filter we also have to create a different datatype (that is, a different subclass), give it a proper and unique name, document it, etc.

KDFunctionalSortFilterProxyModel tries to improve on this situation by offering a functional interface to QSortFilterProxyModel. If you need to customize what a given proxy instance should do, all you need to do is to set a function-like object (a free function, a lambda, etc.) that provides custom filtering and/or custom sorting. For instance:

// create the proxy
KDFunctionalSortFilterProxyModel *proxy = new KDFunctionalSortFilterProxyModel(parent);

// use this lambda as the filtering function
auto acceptFunction = [](const QAbstractItemModel *model, int source_row, const QModelIndex &parent)
{
    // decide whether to accept `source_row` from `model`, under `parent`;
    // return true to accept, false to filter the row out
};

proxy->setFilterAcceptsRowFunction(acceptFunction);

// use it!
proxy->setSourceModel(sourceModel);
view->setModel(proxy);

KDToolBox is freely available here. Thanks for reading, and have a great day!

About KDAB

If you like this article and want to read similar material, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *