Combo Boxes in Item Views

From Qt Wiki
Revision as of 13:13, 5 February 2019 by Christian Ehrlicher (talk | contribs) (Adjusted to current Qt style)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Sample code to use combo boxes as editor widgets in an item view or item widget.

The delegate creates a combo box if the index is in the second column of a list view. For the other columns it just returns the default editor, that QStyledItemDelegate creates.

File comboboxitemdelegate.h


#include <QStyledItemDelegate>

class ComboBoxItemDelegate : public QStyledItemDelegate
    ComboBoxItemDelegate(QObject *parent = nullptr);

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
    void setEditorData(QWidget *editor, const QModelIndex &index) const override;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;


File comboboxitemdelegate.cpp

#include "comboboxitemdelegate.h"
#include <QComboBox>

ComboBoxItemDelegate::ComboBoxItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)


QWidget *ComboBoxItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
    // Create the combobox and populate it
    QComboBox *cb = new QComboBox(parent);
    const int row = index.row();
    cb->addItem(QString("one in row %1").arg(row));
    cb->addItem(QString("two in row %1").arg(row));
    cb->addItem(QString("three in row %1").arg(row));
    return cb;

void ComboBoxItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
    QComboBox *cb = qobject_cast<QComboBox *>(editor);
    // get the index of the text in the combobox that matches the current value of the item
    const QString currentText =;
    const int cbIndex = cb->findText(currentText);
    // if it is valid, adjust the combobox
    if (cbIndex >= 0)

void ComboBoxItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
    QComboBox *cb = qobject_cast<QComboBox *>(editor);
    model->setData(index, cb->currentText(), Qt::EditRole);

File main.cpp

#include <QApplication>
#include <QTableWidget>

#include "comboboxitemdelegate.h"

int main(int argc, char *argv[])
    QApplication a(argc, argv);
    QTableWidget tw;

    ComboBoxItemDelegate* cbid = new ComboBoxItemDelegate(&tw);
    // ComboBox only in column 2 
    tw.setItemDelegateForColumn(1, cbid);

    return a.exec();