Qt自定义控件学习扩展QPushButton

这里不用css的方法来实现,用重画的方法来处理。

效果

Qt自定义控件学习扩展QPushButton_QPushButton

源代码

头文件mybutton.h

#ifndef MYBUTTON_H
#define MYBUTTON_H

#include <QPushButton>
#include <QWidget>
#include <QPainter>
#include <QDebug>


class MyButton : public QPushButton
{
    Q_OBJECT
public:
    //MyButton();
    explicit MyButton(QWidget *parent = nullptr);

    QIcon iconNormal ;//默认图标
    QIcon iconPressed ; //按下的图标
    bool isPressed=false;//是否按下

    void  paintEvent(QPaintEvent *ev);

    //捕获事件
    void enterEvent(QEvent *);//鼠标进入
    void  leaveEvent(QEvent *);   //鼠标离开
};

#endif // MYBUTTON_H

mybutton.cpp

#include "mybutton.h"
#include<QMouseEvent>
MyButton::MyButton(QWidget *parent) : QPushButton(parent)
{
    this->isPressed=false;
    // if (this->icon()==NULL){
    if (this->icon().isNull()){
        qDebug()<<"icon is null";
    }else{
        qDebug()<<"icon is not null";
    }
}


void MyButton::paintEvent(QPaintEvent *ev)
{
    if (icon().isNull() ) {
        // qDebug()<<"按扭的图片为空";
    }else {
        // qDebug()<<"按扭的图片不为空,处理";
        if (iconNormal.isNull() ){
            iconNormal=QIcon(icon());
        }
        if (iconPressed.isNull() ){
            QPixmap pixTemp;            
            pixTemp= icon().pixmap( icon().actualSize(QSize(100, 100)) );
            pixTemp= pixTemp.scaled(100,100,Qt::KeepAspectRatio);
            qDebug()<<pixTemp.width()<<"    "<<pixTemp.height();         

            QPixmap pix(pixTemp.width(),pixTemp.height());
            pix.fill(Qt::transparent);//填充为透明
            QPainter painter(&pix);           
            painter.shear(0,0.5); //扭曲
            painter.drawPixmap(0,0,100,100,pixTemp);             
            iconPressed=QIcon(pix);
        }
        if ( isPressed) {
            setIcon(iconPressed);
        }  else{
            setIcon(iconNormal);
        }
    }

    QPushButton::paintEvent(ev); //继承父类的重画方法  继承重画
}

//鼠标进入
void MyButton::enterEvent(QEvent *){
    isPressed=true;
    update();
}
//鼠标离开
void MyButton::leaveEvent(QEvent *){
    isPressed=false;
    update();
}