Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Last active June 30, 2018 02:43
Show Gist options
  • Save jniemann66/f45c5a7f4ff17df227224b9fc31b7069 to your computer and use it in GitHub Desktop.
Save jniemann66/f45c5a7f4ff17df227224b9fc31b7069 to your computer and use it in GitHub Desktop.
Qt: CheckBoxDelegate class
#include "checkboxdelegate.h"
#include <QApplication>
CheckBoxDelegate::CheckBoxDelegate(QObject *parent) : QStyledItemDelegate(parent), scale(1.1) {}
void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QRect rect(option.rect.left() / scale, option.rect.top() / scale, option.rect.width() / scale, option.rect.height() / scale);
painter->save();
painter->scale(scale, scale);
if (option.state & QStyle::State_Selected)
painter->fillRect(rect, option.palette.highlight());
QStyleOptionButton cbIndicator;
cbIndicator.rect = rect;
cbIndicator.state = QStyle::State_Enabled | (index.data().toBool() ? QStyle::State_On : QStyle::State_Off);
QApplication::style()->drawControl(QStyle::CE_CheckBox, &cbIndicator, painter);
painter->restore();
}
bool CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
if (event->type() == QEvent::MouseButtonRelease)
{
model->setData(index, !index.data().toBool()); // toggle checkbox state
return true;
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
qreal CheckBoxDelegate::getScale() const
{
return scale;
}
void CheckBoxDelegate::setScale(const qreal &value)
{
scale = value;
}
#ifndef CHECKBOXDELEGATE_H
#define CHECKBOXDELEGATE_H
#include <QObject>
#include <QStyledItemDelegate>
#include <QPainter>
class CheckBoxDelegate : public QStyledItemDelegate
{
public:
CheckBoxDelegate(QObject* parent = nullptr);
qreal getScale() const;
void setScale(const qreal &value);
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override;
private:
qreal scale;
};
#endif // CHECKBOXDELEGATE_H
@jniemann66
Copy link
Author

Checkbox for TableWidgets / TableViews
features a scale factor to make the checkboxes a bit bigger, if desired

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment