主なアイデアは、チェックボックス描画のデフォルトの実装をコピーし、必要に応じて変更することです。デフォルトの実装ではラベルの四角形を取得するため、この場所に新しい要素を描画し、ラベルを右にシフトするだけです。また、新しい要素とデフォルト コンテンツの両方が最小サイズに収まるように、サイズ ヒントを調整する必要があります。
class CustomCheckBox : public QCheckBox {
Q_OBJECT
public:
CustomCheckBox(QWidget* parent = 0) : QCheckBox(parent) {
m_decoratorSize = QSize(16, 16);
m_decoratorMargin = 2;
}
QSize minimumSizeHint() const {
QSize result = QCheckBox::minimumSizeHint();
result.setWidth(result.width() + m_decoratorSize.width() + m_decoratorMargin * 2);
return result;
}
protected:
void paintEvent(QPaintEvent*) {
QPainter p(this);
QStyleOptionButton opt;
initStyleOption(&opt);
QStyleOptionButton subopt = opt;
subopt.rect = style()->subElementRect(QStyle::SE_CheckBoxIndicator, &opt, this);
style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &subopt, &p, this);
subopt.rect = style()->subElementRect(QStyle::SE_CheckBoxContents, &opt, this);
p.fillRect(QRect(subopt.rect.topLeft() + QPoint(m_decoratorMargin, 0),
m_decoratorSize), QBrush(Qt::green));
subopt.rect.translate(m_decoratorSize.width() + m_decoratorMargin * 2, 0);
style()->drawControl(QStyle::CE_CheckBoxLabel, &subopt, &p, this);
if (opt.state & QStyle::State_HasFocus) {
QStyleOptionFocusRect fropt;
fropt.rect = style()->subElementRect(QStyle::SE_CheckBoxFocusRect, &opt, this);
fropt.rect.setRight(fropt.rect.right() +
m_decoratorSize.width() + m_decoratorMargin * 2);
style()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, &p, this);
}
}
private:
QSize m_decoratorSize;
int m_decoratorMargin;
};
チェックボックスはプラットフォームごとに大幅に異なるため、このソリューションは移植性がない可能性があることに注意してください。Windowsでのみテストしました。が提供するデフォルトの実装を使用しましたQCommonStyle
。