About delegates and cell renderers - data formatting in Qt
Warning: the following blog post has a rant-to-usefulness ratio of 3:1.
Last week I needed to perform some data formatting on Qt list view. From reading the documentation alone I could not find a satisfying answer. When asking on IRC the answer was to use proxy models. This would have worked, but having two models for one view can create all kind of correspondence problems (think of sorting etc.). And there is this interesting bugreport, complaining that there is no easy way to format data. Status: rejected! So formatting should be a responsibility of the view? Wow, who would have thought ... however, if proxy models are a no-go we are left with ... custom delegates.
(cut some nonsense about MVC)
In the Qt world, a delegate is reponsible for 3 tasks:
- editing contents displayed in a view (possibly by creating new editor widgets on the fly),
- updating the model with the modified contents,
- rendering the contents in a view.
Somehow, that's two tasks too many, for something that is not a controller. That's where I prefersLet's take a look at GTK+ cell renderers: they only perform one task, and that's exactly what their names suggests(correction: actually, they are responsible for editing and updating as well, should have read more). A text cell renderer renders text, a pixbuf cell renderer renders pixbufs, and so on. Simple but tremendously flexible.
So how can I inject this flexibility into delegates? The QItemDelegate won't be very useful unless you want to use a QPainter for everything. But there is this styled item delegate, added with version 4.4 of Qt. And if we look at the roles & accepted types table we can see how this - together with displayText - could translate nicely into Qt "cell renderers". So we create custom styled delegates for each data type we need to display in our view: text delegates, pixmap^Wdecoration delegates ... Once we have defined a set of custom delegate classes we then request the view to use them on a per-row or on a per-column basis. A proof of concept can be found here.
EDIT: Had to correct some nonsense, this post was too much of a rant and I wasn't thinking clearly. What I originally wanted to express was that with QStyledItemDelegate we can have something very similar to GtkCellRenderer and use them both in a very similar way, too. I think the Qt documentation could have been easier to follow with straight and simple formatting data example, hence my rant. Sorry =/