[Solved] QTableView + QAbstractItemDelegate: Custom editor doesnt close on enter or when “clicking away”?
Can someone tell me how to correctly use delegation? I actually want to use QValidator on QTableView “cells”.
Seems that there’s no other way than to delegate.
So I’ve implemented QAbstractItemDelegate::createEditor(), but when editing the cell, the custom created QLineEdit doesn’t close again as it should normally by pressing enter or clicking into the QTableView-viewport (it closes when clicking anywhere on any row though).
What am I missing?
Thanks for your responses.
Before I go with an example, another question, because it seems I got it working now.
closeEditor(…) signal must be emitted by the custom QLineEdit returned in QAbstractItemDelegate::createEditor().
So I subclassed QLineEdit and let it emit closeEditor(…) on return, escape and lost focus.
And then I connected MyLineEdit::closeEditor(…) with QTableView::closeEditor(…).
Now the editor closes properly whenever I click away or press return or escape.
Is this the (a) correct way?
Hmm… I had to inherit my delegate from QItemDelegate, not from QAbstractItemDelegate.
But I saw code using QAbstractItemDelegate I’m sure. I guess I still didn’t get the basics…
Now it works (behaves like default) by just returning a new widget (without frame) in createEditor(), and setting geometry in updateEditorGeometry().
Sure I won’t forget about setEditorData() and setModelData().
It’s generally recommended to use QStyledItemDelegate instead of QItemDelegate.
See the note in the docs [doc.qt.nokia.com]:
QStyledItemDelegate vs. QItemDelegate
Since Qt 4.4, there are two delegate classes: QItemDelegate and QStyledItemDelegate. However, the default delegate is QStyledItemDelegate. These two classes are independent alternatives to painting and providing editors for items in views. The difference between them is that QStyledItemDelegate uses the current style to paint its items. We therefore recommend using QStyledItemDelegate as the base class when implementing custom delegates or when working with Qt style sheets. The code required for either class should be equal unless the custom delegate needs to use the style for drawing.
Problem with that is, that the API of both delegates are completely different. Some things that were easy with QItemDelegate are neigh on inmpossible with QStyledItemDelegate. If you can manage what you need to do with QStyledItemDelegate, then that is obviously the way to go, but otherwise QItemDelegate is still an option, IMHO.