CheckBoxDelegate.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "CheckBoxDelegate.h"
  2. #include <QCheckBox>
  3. #include <QPainter>
  4. #include <QApplication>
  5. CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
  6. : QStyledItemDelegate(parent)
  7. {
  8. }
  9. CheckBoxDelegate::~CheckBoxDelegate()
  10. {
  11. }
  12. QWidget* CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
  13. {
  14. // QCheckBox *checkBox = new QCheckBox(parent);
  15. // checkBox->setText("Check me");
  16. // return checkBox;
  17. return nullptr;
  18. }
  19. void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
  20. {
  21. }
  22. void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
  23. {
  24. }
  25. void CheckBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
  26. {
  27. }
  28. void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
  29. {
  30. // 获取复选框状态
  31. bool checked = index.data(Qt::CheckStateRole).toInt() == Qt::Checked;
  32. // 获取文本
  33. QString text = index.data(Qt::DisplayRole).toString();
  34. QStyleOptionButton checkBoxOption;
  35. QRect checkBoxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkBoxOption);
  36. checkBoxOption.rect = QRect(option.rect.left(), option.rect.top() + (option.rect.height() - checkBoxRect.height()) / 2, checkBoxRect.width(), checkBoxRect.height());
  37. checkBoxOption.state = QStyle::State_Enabled | (checked ? QStyle::State_On : QStyle::State_Off);
  38. // 绘制复选框
  39. QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkBoxOption, painter);
  40. // 绘制文本
  41. QRect textRect = option.rect;
  42. textRect.setLeft(checkBoxOption.rect.right() + 4); // 复选框后留点间距
  43. painter->drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, text);
  44. }
  45. bool CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
  46. {
  47. if (event->type() == QEvent::MouseButtonRelease)
  48. {
  49. // Handle checkbox toggle logic here
  50. bool currentState = index.data(Qt::CheckStateRole).toBool();
  51. model->setData(index, !currentState, Qt::CheckStateRole);
  52. return true;
  53. }
  54. return QStyledItemDelegate::editorEvent(event, model, option, index);
  55. }