Qt自定义控件13:继承QPushButton自绘按钮

Qt自定义控件13:继承QPushButton自绘按钮

先看效果图:Qt自定义控件13:继承QPushButton自绘按钮_第1张图片

思路:新建类继承QPushButton,重写paintEvent方法,根据需求画出界面。(效果图是通过拖的QPushButton控件,然后提升为我的自定义类进行操作)

关键代码:

CMButton::CMButton(QWidget *parent) :QPushButton(parent)
{
    setCheckable(true);
    QFontMetrics fontMetrics(font());
    int nFontWidth = fontMetrics.width(this->text());
    this->setMinimumWidth(nFontWidth+this->iconSize().width()+iconStartX);
    textStartX = iconSize().width()+iconStartX;
}

void CMButton::paintEvent(QPaintEvent *event){
    //绘制准备工作,启用反锯齿
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    drawBg(&painter);
    drawText(&painter);
    drawIcon(&painter);
    drawTri(&painter);
    drawLine(&painter);
}

void CMButton::drawBg(QPainter* painter){
    int width = this->width();
    int height = this->height();
    painter->save();
    if(isChecked()){
        painter->setBrush(checkBgColor);
    }else if(isHovered){
        painter->setBrush(hoverBgColor);
    }else{
        painter->setBrush(normalBgColor);
    }
    QRect rect(0,0,width,height);
    painter->setPen(Qt::NoPen);
    painter->drawRect(rect);
    painter->restore();
}

void CMButton::drawText(QPainter *painter){
    painter->save();
    QRect rect(textStartX,0,this->width(),this->height());
    if(isChecked()){
        painter->setPen(checkTextColor);
    }else if(isHovered){
        painter->setPen(hoverTextColor);
    }else{
        painter->setPen(normalTextColor);
    }

    QFont font = painter->font();
//    font.setPixelSize(10);
    painter->setFont(font);
    painter->drawText(rect,Qt::AlignCenter,text());
    painter->restore();
}

void CMButton::drawIcon(QPainter *painter){
    painter->save();
    QRect rect(iconStartX,(this->height()-this->iconSize().height())/2,this->iconSize().width(),this->iconSize().height());
    QPixmap pixmap = this->icon().pixmap(this->iconSize());
    painter->drawPixmap(rect,pixmap);
    painter->restore();
}

void CMButton::drawTri(QPainter *painter){
    painter->save();

    painter->restore();
}

void CMButton::drawLine(QPainter *painter){
    painter->save();
    if(isChecked() || isHovered){
        QRect rect(0,0,5,this->height());
        painter->setPen(Qt::NoPen);
        painter->setBrush(lineColor);
        painter->drawRect(rect);
    }

    painter->restore();
}

void CMButton::enterEvent(QEvent *)
{
    isHovered = true;
    update();
}

void CMButton::leaveEvent(QEvent *)
{
    isHovered = false;
    update();
}

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