Let’s check the final result first
checkbox
code snippets:
/*************** head file **********************/
class CheckBox : public QWidget{
Q_OBJECT
public:
CheckBox(QWidget * parent = nullptr);
void mousePressEvent(QMouseEvent *event) ;
void paintEvent(QPaintEvent *event);
void enterEvent(QEvent *event) ;
void leaveEvent(QEvent *event) ;
public:
bool isChecked();
signals:
void sigChecked(bool check);
private:
bool checked;
bool hovering;
};
/********************** cpp file ***********************/
CheckBox::CheckBox(QWidget * parent):QWidget(parent){
this->setFixedSize(32,32);
setAutoFillBackground(true);
setStyleSheet("border:none");
setMouseTracking(true);
checked = false;
hovering = false;
}
void CheckBox::enterEvent(QEvent *event) {
hovering = true;
update();
}
void CheckBox::leaveEvent(QEvent *event) {
hovering = false;
update();
}
void CheckBox::mousePressEvent(QMouseEvent *event) {
checked = !checked;
this->update();
emit sigChecked(checked);
}
void CheckBox::paintEvent(QPaintEvent *event) {
static const QString colorNorm = skinList[SkinPink].normal;
static const QString colorHov = skinList[SkinPink].hover;
static const QString colorPress = skinList[SkinPink].pressed;
auto rect = this->rect();
rect.adjust(4,4,-4,-4);
QPainter p(this);
p.setRenderHints(QPainter::Antialiasing);
QPen pen;
QBrush brush;
if(hovering) brush = QBrush(QColor(colorHov));
else brush = QBrush(QColor(colorNorm));
pen.setWidth(2);
pen.setColor(QColor(colorPress));
p.setPen(pen);
brush.setTransform(QTransform(1.03,0,1,0,1.03,1));
p.setBrush(brush);
p.drawRoundedRect(rect,6,6);
if(checked){
int x = width();
int y = height();
QPainterPath pp;
pp.moveTo(x/4,y/2);
pp.lineTo(0.375*x,0.75*y);
pp.lineTo(0.75*x,0.25*y);
p.drawPath(pp);
}
}