ComboBoxDelegate.h文件
#ifndef COMBOBOXDELEGATE_H
#define COMBOBOXDELEGATE_H
#include <QObject>
#include <QStyledItemDelegate>
#include <QComboBox>
class ComboBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ComboBoxDelegate( QObject *parent = nullptr);
void setItems(const QStringList &texts);
public:
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;
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
QStringList _texts;
};
#endif
ComboBoxDelegate.cpp文件
#include "ComboBoxDelegate.h"
ComboBoxDelegate::ComboBoxDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
void ComboBoxDelegate::setItems(const QStringList &texts)
{
_texts = texts;
}
QWidget* ComboBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QComboBox *editor = new QComboBox(parent);
editor->addItems(_texts);
return editor;
}
void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString text = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
int tindex = comboBox->findText(text);
comboBox->setCurrentIndex(tindex);
}
void ComboBoxDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString text = comboBox->currentText();
model->setData(index, text, Qt::EditRole);
}
void ComboBoxDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem viewOption(option);
initStyleOption(&viewOption, index);
QStyledItemDelegate::paint(painter, viewOption, index);
}
使用
ComboBoxDelegate* m_cbDlg = new ComboBoxDelegate;
m_tableWidget->setItemDelegateForColumn(0, m_cbDlg)
QStringList items;
items << QString("类型1")
<< QString("类型2")
<< QString("类型3");
m_cbDlg->setItems(items);
示例工程