Last active
June 30, 2018 02:43
-
-
Save jniemann66/f45c5a7f4ff17df227224b9fc31b7069 to your computer and use it in GitHub Desktop.
Qt: CheckBoxDelegate class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Checkbox for TableWidgets / TableViews
features a scale factor to make the checkboxes a bit bigger, if desired