Qt自定义控件14:选择框(内部添加文字版)

Qt自定义控件14:选择框(内部添加文字版)

先看效果图:
Qt自定义控件14:选择框(内部添加文字版)_第1张图片

思路:与前面的选择框相同,只是在那基础上寻找另外一个矩形的位置添加文字

关键代码:

void CMCheckBox2::paintEvent(QPaintEvent *){
    QPainter painter(this);
    //反锯齿
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    paintBackG(&painter);
    paintIn(&painter);
    paintInE(&painter);
    paintText(&painter);
}

void CMCheckBox2::paintBackG(QPainter *painter){
    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(Qt::white);
    QPainterPath path;
    QRect rectOut(0,0,this->width(),this->height());
    path.addRoundedRect(rectOut,this->height()/2,this->height()/2);
    painter->drawPath(path);

    painter->restore();
}

void CMCheckBox2::paintIn(QPainter *painter){
    painter->save();
    painter->setPen(Qt::NoPen);
    if(isChecked()){
        painter->setBrush(QColor("#4CB501"));
    }else{
        painter->setBrush(QColor("#747E81"));
    }

    QPainterPath path;
    QRect rectInn(outSide,outSide,this->width()-outSide*2,this->height()-outSide*2);
    path.addRoundedRect(rectInn,(this->height()-outSide*2)/2,(this->height()-outSide*2)/2);
    painter->drawPath(path);
    painter->restore();
}

void CMCheckBox2::paintInE(QPainter *painter){
    painter->save();
    painter->setPen(Qt::NoPen);
    if(isChecked()){
        QRect rect(this->width()-(this->height()-outSide*2)-outSide,outSide,this->height()-outSide*2,this->height()-outSide*2);
        painter->setBrush(Qt::white);
        painter->drawEllipse(rect);

    }else{
        QRect rect(outSide,outSide,this->height()-outSide*2,this->height()-outSide*2);
        painter->setBrush(Qt::white);
        painter->drawEllipse(rect);
    }
    painter->restore();
}

void CMCheckBox2::paintText(QPainter *painter){
    painter->save();
    painter->setPen(Qt::white);
    QFont font = painter->font();
    font.setFamily("Microsoft YaHei");
    painter->setFont(font);
    if(isChecked()){
        QRect rect(outSide,outSide,this->width()-(this->height()-outSide*2+outSide),this->height()-outSide*2);
        painter->drawText(rect,Qt::AlignCenter,QString("已开启"));
    }else{
        QRect rect((this->height()-outSide*2)+outSide,outSide,this->width()-(this->height()-outSide*2+outSide),this->height()-outSide*2);
        painter->drawText(rect,Qt::AlignCenter,QString("未开启"));
    }
    painter->restore();
}
void CMCheckBox2::mousePressEvent(QMouseEvent *e){
    setChecked(!isChecked());
    update();
}

你可能感兴趣的:(Qt画图(自定义控件))