Based on the idea provided by Jason, I came up with this solution.
To launch the editor on single click, I connected QAbstractItemView::clicked(const QModelIndex &index)
signal of my view, to QAbstractItemView::edit(const QModelIndex &index)
slot of that same view.
If you use Qt4, you need to create a slot in your delegate. Pass your combobox as an argument to this slot. In this slot you call QComboBox::showPopup
. So it will look like this:
void MyDelegate::popUpComboBox(QComboBox *cb)
{
cb->showPopup();
}
But first we need to register the QComboBox*
type. You can call this in the constructor of your delegate:
qRegisterMetaType<QComboBox*>("QComboBox*");
The reason we need this slot, is because we can't show the pop up straight away in MyDelegate::createEditor
, because the position and the rect of the list view are unknown. So what we do is in MyDelegate::createEditor
, we call this slot with a queued connection:
QComboBox *cb = new QComboBox(parent);
// populate your combobox...
QMetaObject::invokeMethod(const_cast<MyDelegate*>(this), "popUpComboBox", Qt::QueuedConnection, Q_ARG(QComboBox*, cb));
This will show the list view of the combobox correctly when the editor is activated.
Now if you are using Qt5, the slot is not needed. All you do is call QComboBox::showPopup
with a queued connection from MyDelegate::createEditor
. The easiest way to do this is with a QTimer
:
QTimer::singleShot(0, cb, &QComboBox::showPopup);
For some extra information, this is how you can paint the combobox so it is shown all the time, not only when the editor is shown:
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.column() == 1) // show combobox only in the second column
{
QStyleOptionComboBox box;
box.state = option.state;
box.rect = option.rect;
box.currentText = index.data(Qt::EditRole).toString();
QApplication::style()->drawComplexControl(QStyle::CC_ComboBox, &box, painter, 0);
QApplication::style()->drawControl(QStyle::CE_ComboBoxLabel, &box, painter, 0);
return;
}
QStyledItemDelegate::paint(painter, option, index);
}
tableView->setEditHint(QAbstractItemView::SelectedClicked);
– ShowroomsetEditHint
here harmattan-dev.nokia.com/docs/library/html/qt4/… – Monofilament