#include "Listview_delgate.h" #include #include #include Listview_delgate::Listview_delgate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget *Listview_delgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) if (!index.isValid()) return nullptr; QComboBox *editor = new QComboBox(parent); editor->setModel(index.model()->data(index, Qt::EditRole).value()); return editor; } void Listview_delgate::setEditorData(QWidget *editor, const QModelIndex &index) const { if (!index.isValid()) return; QComboBox *comboBox = qobject_cast(editor); if (comboBox) { QString currentText = index.model()->data(index, Qt::EditRole).toString(); int currentIndex = comboBox->findText(currentText); comboBox->setCurrentIndex(currentIndex); } } void Listview_delgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (!index.isValid()) return; QComboBox *comboBox = qobject_cast(editor); if (comboBox) { QString selectedText = comboBox->currentText(); model->setData(index, selectedText, Qt::EditRole); } } void Listview_delgate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyledItemDelegate::paint(painter, option, index); if (index.parent().isValid()) { // 设置字体颜色为白色 painter->setPen(Qt::white); // 绘制文本 QString text = index.data(Qt::DisplayRole).toString(); painter->drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, text); } }