12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #include "Listview_delgate.h"
- #include <QComboBox>
- #include <QStyledItemDelegate>
- #include <QPainter>
- 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<QAbstractListModel*>());
- return editor;
- }
- void Listview_delgate::setEditorData(QWidget *editor, const QModelIndex &index) const
- {
- if (!index.isValid())
- return;
- QComboBox *comboBox = qobject_cast<QComboBox*>(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<QComboBox*>(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);
- }
- }
|