views:

265

answers:

2

Does anyone have an example of using a QWidget as an editor in a QAbstractTableModel?
I have a column which when edited should create a QCombobox with the list of choices.

The docs seem to suggest I need to write a QAbstractItemDelegate and a custom paint function but that seems overkill to simply pop-up a standard QCombobox in Qt::EditRole.

Note - the combo box contents are the same for every row and it only needs to be shown when somebody clicks in the cell.

I know this should be simple but I can't get it to work. It's easy for a QTableWidget based table - but I need it for a very large data table.

+3  A: 

The docs seem to suggest I need to write a QAbstractItemDelegate and a custom paint function but that seems overkill to simply pop-up a standard QCombobox in Qt::EditRole.

You don't need to go that far. One way is to subclass QStyledItemDelegate and then override createEditor() so that it returns your prepopulated combo box. Its setEditorData and setModelData functions will probably already suffice if you`re using basic Qt value types.

If you need something more generic that works across many different models, you can create a QItemEditorFactory that associates your editor with the correct type. This also works well with custom types.

When indicated by your view's EditTrigger, your view will get the delegate specific to the cell on which the edit is being invoked and call delegate->createEditor(...) which can then size the combo box according to the options parameter as well as set the current entry to the value specified by the model, although most of this should be handled by the QStyledItemDelegate. Thus, you won't have to worry about the Qt::EditRole directly as the view will handle that.

Kaleb Pederson
Thanks that helped - how do I actually hook the delegate into the Qt::Editrole in QAbstractTableModel?
Martin Beckett
Answer updated to discuss how editing is invoked.
Kaleb Pederson
Thats what I though but it wasn't working. I found the spinbox example - once you had given me the "QStyledItemDelegate" thank you
Martin Beckett
+1  A: 

Hey,

Did you try and have a look at the following example from Qt :

Spin Box Delegate Example

Maybe it will give you a much clearer view on the subject !

Hope it helps a bit !

Andy M
Thanks - found it just after I posted the comment!
Martin Beckett