#include "cellsmonitorcheckboxdelegate.h" #include #include #include CheckBoxDelegate::CheckBoxDelegate(QObject *parent) :QStyledItemDelegate (parent) { m_circleSize = 15; } QWidget *CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index) //Cоздаем checkbox editor QCheckBox *editor = new QCheckBox(parent); return editor; } void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { //Установливаем выбрано/не выбрано QCheckBox *cb = qobject_cast(editor); cb->setStyleSheet("QCheckBox::indicator {\n width: 20px;\n height: " + QString::number( m_circleSize ) + "px;\n border: 1px solid grey;\n background: white;\n border-radius:3px;\n} \n\nQCheckBox::indicator:checked {\n border-color: green;\n background: green;\n color:white;\n /*image: url(:/res/checkbox_unchecked_hover.png);*/\n} \n\n\n\nQCheckBox {\n font-weight:bold;\n font-size: 14px;\n}"); cb->setChecked(index.data().toBool()); } void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { //Записываем данные в модель QCheckBox *cb = static_cast(editor); int value = (cb->checkState()==Qt::Checked)? 1 : 0; model->setData(index, value, Qt::EditRole); } void CheckBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); QStyleOptionButton checkboxstyle; QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle); //Центрирование checkboxstyle.rect = option.rect; checkboxstyle.rect.setLeft(option.rect.x() + option.rect.width()/2 - checkbox_rect.width()/2); editor->setGeometry(checkboxstyle.rect); } void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int row = index.row(); int col = index.column(); painter->save(); //Получаем данные auto data = index.model()->data(index, Qt::DisplayRole); //Создаем стиль CheckBox QStyleOptionButton checkboxstyle; //Выбрано или не выбрано bool isChecked = data.toBool(); if(data.toBool()) checkboxstyle.state = QStyle::State_On|QStyle::State_Enabled; else checkboxstyle.state = QStyle::State_Off|QStyle::State_Enabled; if(!index.data().isNull()) { QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle); //Центрирование checkboxstyle.rect = option.rect; checkboxstyle.rect.setLeft(option.rect.x() + option.rect.width()/2 - checkbox_rect.width()/2); RectangleClass r; int centerX = option.rect.width()/2 - m_circleSize/2; int centerY = option.rect.height()/2 - m_circleSize/2; r.draw ( painter, QRectF( option.rect.x() + centerX, //+mx, option.rect.y() + centerY, //+my, m_circleSize, m_circleSize ), isChecked ? QColor("#009352") // green : QColor("#dfe0eb"), 11 ); } else { RectClass r; QRectF rectT( option.rect ); r.draw ( painter, rectT ); } painter->restore(); }