Qt-interest Archive, March 2008
custom models with multiple delegates
Message 1 in thread
I have a custom model with multiple items, each with different editing
characteristics. It seems my View needs to know too much about the items
in order to set the proper delegates (per row, I guess, since one
delegate type won't do it). Shouldn't the Model be able to tell the view
what delegate it needs depending on the index?
For example, say I have an index that is a number and I want to edit it
with a spin-box, and I have another index that is a list and I want a
ComboBox editor. I need two delegates for this, one with a spin-box and
another with the combo-box, and then I need a way to associate the
delegates with each index. The only API the view (say, a TreeView) gives
me is setItemDelegateForRow(), but I have to call this myself when the
view notices new items have been exposed through the model.
Shouldn't one of the data roles of a model to be which delegate to use?
Then I can encapsulate all of the knowledge about viewing/editing in the
model, and the View can remain simpler.
Or, at the very least, make itemDelegate(const QModelIndex &) virtual so
I can just subclass the view and return the appropriate one.
Does anyone have any advice on managing this kind of scenario?
--
[ signature omitted ]
Message 2 in thread
On 04.03.08 12:59:23, Paul Miller wrote:
> I have a custom model with multiple items, each with different editing
> characteristics. It seems my View needs to know too much about the items in
> order to set the proper delegates (per row, I guess, since one delegate
> type won't do it). Shouldn't the Model be able to tell the view what
> delegate it needs depending on the index?
>
> For example, say I have an index that is a number and I want to edit it
> with a spin-box, and I have another index that is a list and I want a
> ComboBox editor. I need two delegates for this,
No you don't, you just need your own delegate class which knows what
editor to create for each index. See QItemDelegate api dox.
> Shouldn't one of the data roles of a model to be which delegate to use?
No, because a model just delivers data (in fact even the
foreground/background roles are just convenience, the "right way" is to
implement the drawing in the delegate).
> Then I can encapsulate all of the knowledge about viewing/editing in the
> model, and the View can remain simpler.
How the data of each index is drawn is not part of the view, but part of
the delegate. This includes the editor to use.
> Or, at the very least, make itemDelegate(const QModelIndex &) virtual so I
> can just subclass the view and return the appropriate one.
There's setItemDelegate() on the view and you can just subclass
QItemDelegate and write whatever code you need.
Check the interview documentation for some examples how to provide your
own editor.
Andreas
--
[ signature omitted ]