123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- #include "CheckBoxDelegate.h"
- #include <QCheckBox>
- #include <QPainter>
- #include <QApplication>
- CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
- : QStyledItemDelegate(parent)
- {
- }
- CheckBoxDelegate::~CheckBoxDelegate()
- {
- }
- QWidget* CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
- {
- // QCheckBox *checkBox = new QCheckBox(parent);
- // checkBox->setText("Check me");
- // return checkBox;
- return nullptr;
- }
- void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
- {
- }
- void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
- {
- }
- void CheckBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
- {
- }
- void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
- {
- // 获取复选框状态
- bool checked = index.data(Qt::CheckStateRole).toInt() == Qt::Checked;
- // 获取文本
- QString text = index.data(Qt::DisplayRole).toString();
- QStyleOptionButton checkBoxOption;
- QRect checkBoxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkBoxOption);
- checkBoxOption.rect = QRect(option.rect.left(), option.rect.top() + (option.rect.height() - checkBoxRect.height()) / 2, checkBoxRect.width(), checkBoxRect.height());
- checkBoxOption.state = QStyle::State_Enabled | (checked ? QStyle::State_On : QStyle::State_Off);
- // 绘制复选框
- QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkBoxOption, painter);
- // 绘制文本
- QRect textRect = option.rect;
- textRect.setLeft(checkBoxOption.rect.right() + 4); // 复选框后留点间距
- painter->drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, text);
- }
- bool CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
- {
- if (event->type() == QEvent::MouseButtonRelease)
- {
- // Handle checkbox toggle logic here
- bool currentState = index.data(Qt::CheckStateRole).toBool();
- model->setData(index, !currentState, Qt::CheckStateRole);
- return true;
- }
- return QStyledItemDelegate::editorEvent(event, model, option, index);
- }
|