18 #include <QApplication>
21 #include <QMouseEvent>
23 #include <QStyleOptionButton>
28 const QStyleOptionViewItem& option,
29 const QModelIndex& index)
const
33 bool checked = index.model()->data(index, Qt::DisplayRole).toBool();
35 QStyleOptionButton styleOptionButton;
36 styleOptionButton.state |= QStyle::State_Enabled;
39 styleOptionButton.state |= QStyle::State_On;
43 styleOptionButton.state |= QStyle::State_Off;
48 QApplication::style()->drawControl(QStyle::CE_CheckBox,
49 &styleOptionButton, painter);
53 QItemDelegate::paint(painter, option, index);
58 const QStyleOptionViewItem& option,
59 const QModelIndex& index)
63 if ((event->type() == QEvent::MouseButtonRelease) ||
64 (event->type() == QEvent::MouseButtonDblClick))
66 auto* mouse_event =
static_cast<QMouseEvent*
>(event);
67 if (mouse_event->button() != Qt::LeftButton ||
72 if (event->type() == QEvent::MouseButtonDblClick)
77 else if (event->type() == QEvent::KeyPress)
79 if (
static_cast<QKeyEvent*
>(event)->key() != Qt::Key_Space &&
80 static_cast<QKeyEvent*
>(event)->key() != Qt::Key_Select)
90 bool checked = index.model()->data(index, Qt::DisplayRole).toBool();
91 return model->setData(index, !checked, Qt::EditRole);
95 const QModelIndex& index)
const
100 return QSize(rect.width(), rect.height());
104 const QStyleOptionViewItem& viewItemStyleOptions)
const
106 QStyleOptionButton styleOptionButton;
107 QRect rect = QApplication::style()->subElementRect(
108 QStyle::SE_CheckBoxIndicator, &styleOptionButton);
109 QPoint point(viewItemStyleOptions.rect.x() +
110 viewItemStyleOptions.rect.width() / 2 - rect.width() / 2,
111 viewItemStyleOptions.rect.y() +
112 viewItemStyleOptions.rect.height() / 2 -
114 return QRect(point, rect.size());
Definition of the CheckboxDelegate class.
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Paints a checkbox. This overrides the default painting of a combo box.
QRect checkboxRect(const QStyleOptionViewItem &viewItemStyleOptions) const
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override
Handles the click events and sets the model data.
CheckboxDelegate(QObject *parent=nullptr)
Constructor.