QAbstractItemDelegate 类用于显示和编辑模型中的数据项。
QAbstractItemDelegate 为模型/视图架构中的委托提供接口和通用功能。 委托在视图中显示单个项目,并处理模型数据的编辑。
QAbstractItemDelegate 类是模型/视图类之一,是 Qt 模型/视图框架的一部分。
要以自定义方式呈现项目,您必须实现paint() 和sizeHint()。 QItemDelegate 类为这些函数提供了默认实现; 如果您不需要自定义渲染,请改为对该类进行子类化。
运行效果图:
源码如下:
QWidget* CustomizedItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QWidget* ret = NULL;
m_index = index;
if(QVariant::Bool == index.data(Qt::DisplayRole).type())
{
QCheckBox* check = new QCheckBox(parent);
check->setText(QString::fromLocal8Bit("文官"));
ret = check;
}
else if(QVariant::Char == index.data(Qt::DisplayRole).type())
{
QComboBox* combo = new QComboBox(parent);
combo->addItem("A");
combo->addItem("B");
combo->addItem("C");
combo->addItem("D");
combo->addItem("E");
ret = combo;
}
else
{
ret = QItemDelegate::createEditor(parent, option, index);
}
return ret;
}
void CustomizedItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index);
editor->setGeometry(option.rect);
}
void CustomizedItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if(QVariant::Bool == index.data(Qt::DisplayRole).type())
{
QCheckBox* check = qobject_cast<QCheckBox*>(editor);
if(check != NULL)
{
check->setChecked(index.data().toBool());
}
}
else if(QVariant::Char == index.data(Qt::DisplayRole).type())
{
QComboBox* combo = dynamic_cast<QComboBox*>(editor);
if(NULL != combo)
{
for(int i=0; i<combo->count(); i++)
{
if(combo->itemText(i) == index.data().toString())
{
combo->setCurrentIndex(i);
break;
}
}
}
}
else
{
QItemDelegate::setEditorData(editor, index);
}
}
void CustomizedItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if(QVariant::Bool == index.data(Qt::DisplayRole).type())
{
QCheckBox* check = qobject_cast<QCheckBox*>(editor);
if(NULL != check)
{
model->setData(index, check->isChecked(), Qt::DisplayRole);
}
}
else if(QVariant::Char == index.data(Qt::DisplayRole).type())
{
QComboBox* combo = dynamic_cast<QComboBox*>(editor);
if(NULL != combo)
{
model->setData(index, combo->currentText().at(0), Qt::DisplayRole);
}
}
else
{
QItemDelegate::setModelData(editor, model, index);
}
}
void CustomizedItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if(m_index != index)
{
QItemDelegate::paint(painter, option, index);
}
}
void CustomizedItemDelegate::OnCloseEditor()
{
m_index = QModelIndex();
}
源码:https://download.csdn.net/download/weixin_41937297/35656492