listview_delgate.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "Listview_delgate.h"
  2. #include <QComboBox>
  3. #include <QStyledItemDelegate>
  4. #include <QPainter>
  5. Listview_delgate::Listview_delgate(QObject *parent)
  6. : QStyledItemDelegate(parent)
  7. {
  8. }
  9. QWidget *Listview_delgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
  10. {
  11. Q_UNUSED(option)
  12. if (!index.isValid())
  13. return nullptr;
  14. QComboBox *editor = new QComboBox(parent);
  15. editor->setModel(index.model()->data(index, Qt::EditRole).value<QAbstractListModel*>());
  16. return editor;
  17. }
  18. void Listview_delgate::setEditorData(QWidget *editor, const QModelIndex &index) const
  19. {
  20. if (!index.isValid())
  21. return;
  22. QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
  23. if (comboBox)
  24. {
  25. QString currentText = index.model()->data(index, Qt::EditRole).toString();
  26. int currentIndex = comboBox->findText(currentText);
  27. comboBox->setCurrentIndex(currentIndex);
  28. }
  29. }
  30. void Listview_delgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
  31. {
  32. if (!index.isValid())
  33. return;
  34. QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
  35. if (comboBox)
  36. {
  37. QString selectedText = comboBox->currentText();
  38. model->setData(index, selectedText, Qt::EditRole);
  39. }
  40. }
  41. void Listview_delgate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
  42. {
  43. QStyledItemDelegate::paint(painter, option, index);
  44. if (index.parent().isValid())
  45. {
  46. // 设置字体颜色为白色
  47. painter->setPen(Qt::white);
  48. // 绘制文本
  49. QString text = index.data(Qt::DisplayRole).toString();
  50. painter->drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, text);
  51. }
  52. }