利用重写样式为QPushButton设置背景图片

#include
//该类用来设置背景图片
class StyleImge:public QCommonStyle{ Q_OBJECT //子类化 QCommonStyle 类#include
       QPixmap m_Raised;
       QPixmap m_Press;
       QPixmap m_select;
       //想优化内存的话可以用QMap,来装QPixmap,通过判断Key来区分或者有没有QPixmap
public:StyleImge(){}
      StyleImge(QPixmap Raised ,QPixmap Press=QPixmap(),QPixmap select=QPixmap()  ){
          m_Raised=Raised;
          if(Press.isNull()){

          }else{
              m_Press=Press;
          }
          if(select.isNull()){

          }else{
              m_select=select;
          }
        }
// //这个类的父类的析构不是虚函数,所以父类无法调用子类析构函数,例如:parent *p = new child();delete p;   //父类析构函数是虚函数时,先调用子类的析构函数,再调用父类的析构函数
//       virtual ~StyleImge(){
//            if(m_Raised)delete m_Raised;m_Raised = NULL;
//            if(m_Press)delete m_Press;m_Press = NULL;
//            if(m_select)delete m_select;m_select = NULL;
//        }

//重新实现 drawControl()函数以绘制控件的自定义外观(本示例用于绘制一个 QPushButton)
void drawControl(ControlElement e, const QStyleOption *op,
 QPainter *pr, const QWidget *w = Q_NULLPTR) const{
QPen pn(QColor(1,111,1)); //绿色
 QBrush RaisedColor(QColor(191,191,191)); //灰色
 QBrush PressColor(QColor(161,161,161)); //深灰色
 QBrush selectColor(QColor(222,222,222)); //白色
//参数 op,携带了绘制部件时的状态及其他一些信息。本示例绘制的是按钮,
//因此把 op 转换为 QStyleOptionButton 类型。
 const QStyleOptionButton *pb=qstyleoption_cast(op);
 QRect r=pb->rect; //获取设置的按钮的大小
//若鼠标进入按钮则使用白色填充其背景pr->drawPixmap(r, background);
 if(pb->state&QStyle::State_MouseOver) {
     pr->fillRect(r,selectColor);
     if(!m_select.isNull()){pr->drawPixmap(r, m_select); }else if(!m_Raised.isNull())pr->drawPixmap(r, m_Raised);
 }
//若按钮处于凸起状态(通常为未选被按下状态),则使用灰色填充其背景。
//注意:凸起状态和鼠标进入按钮的状态,二者只能存在其一。没选中
 else if(pb->state&QStyle::State_Raised) { pr->fillRect(r,RaisedColor);if(!m_Raised.isNull())pr->drawPixmap(r, m_Raised); }
//若按钮被按下,则使用灰色填充其背景
 if(pb->state&QStyle::State_Sunken) { pr->fillRect(r,PressColor);
     if(!m_Press.isNull()){pr->drawPixmap(r, m_Press);}else if(!m_Raised.isNull())pr->drawPixmap(r, m_Raised);
 }
//当按钮具有焦点时,绘制按钮的焦点边框
// if(pb->state&QStyle::State_HasFocus) {
// pr->save(); pn.setWidth(4); pn.setStyle(Qt::DashLine); pr->setPen(pn);
// pr->drawRect(r.adjusted(1,1,-2,-2)); pr->restore(); }
//绘制按钮显示的文本。
 pr->drawText(r,Qt::AlignCenter,pb->text);
 }
void polish(QWidget *w){
//设置 Qt::WA_Hover 属性后,将使鼠标在进入或离开部件时产生绘制事件。
w->setAttribute(Qt::WA_Hover,true); }
void unpolish(QWidget *w){ w->setAttribute(Qt::WA_Hover,false); }
};

#endif // M_H

以上为.h文件

使用方法:

new一个按钮,设置样式style

QPushButton *pb1=new QPushButton("AAA",&w);
pb1->setStyle(new StyleImge());

或者

QPixmap Raised;//背景图片

pb1->setStyle(new StyleImge(Raised));

你可能感兴趣的:(QT,GDI+,qt5)