1#ifndef CHECKBOXDELEGATE_H
2#define CHECKBOXDELEGATE_H
4#include "qapplication.h"
6#include <QStyledItemDelegate>
14 : QStyledItemDelegate(parent) {
17 void paint(QPainter *painter,
const QStyleOptionViewItem &option,
18 const QModelIndex &index)
const override {
19 if (index.data().canConvert<
bool>()) {
20 bool checked = index.data().toBool();
22 if (option.state & QStyle::State_Selected)
23 painter->fillRect(option.rect, option.palette.highlight());
25 QStyleOptionButton checkboxStyleOption;
26 checkboxStyleOption.state = QStyle::State_Enabled | (checked ? QStyle::State_On : QStyle::State_Off);
27 checkboxStyleOption.rect = checkBoxRect(option);
29 QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxStyleOption, painter);
31 QStyledItemDelegate::paint(painter, option, index);
36 const QStyleOptionViewItem &option,
37 const QModelIndex &index)
const override {
38 QCheckBox *editor =
new QCheckBox(parent);
42 void setEditorData(QWidget *editor,
const QModelIndex &index)
const override {
43 QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor);
44 bool checked = index.data().toBool();
45 checkBox->setChecked(checked);
48 void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index)
const override {
49 QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor);
50 bool checked = checkBox->isChecked();
51 model->setData(index, checked);
54 void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index)
const override {
55 editor->setGeometry(checkBoxRect(option));
59 QRect checkBoxRect(
const QStyleOptionViewItem &option)
const {
60 QStyleOptionButton checkboxStyleOption;
61 QRect checkboxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxStyleOption);
62 QPoint checkboxPoint(option.rect.x() + option.rect.width() / 2 - checkboxRect.width() / 2,
63 option.rect.y() + option.rect.height() / 2 - checkboxRect.height() / 2);
64 return QRect(checkboxPoint, checkboxRect.size());
Definition checkboxdelegate.h:9
QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Definition checkboxdelegate.h:35
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Definition checkboxdelegate.h:17
void setEditorData(QWidget *editor, const QModelIndex &index) const override
Definition checkboxdelegate.h:42
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Definition checkboxdelegate.h:54
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override
Definition checkboxdelegate.h:48
CheckboxDelegate(QObject *parent=nullptr)
Definition checkboxdelegate.h:13