QPushButton改变形状

改变QPushButton形状

#ifndef CIMAGEBUTTON_H
#define CIMAGEBUTTON_H

#include 

class CImageButton : public QPushButton
{
	Q_OBJECT

public:
	CImageButton(QWidget *parent);
	~CImageButton();
	void SetPixmap(QPixmap* pNormal,QPixmap* pHover,QPixmap* pLighted);
	void SetLighted(bool value);
public:
	void paintEvent(QPaintEvent* pEvent);
	void mousePressEvent(QMouseEvent *e);
	void mouseReleaseEvent(QMouseEvent *e);
	void enterEvent(QEvent *e);
	void leaveEvent(QEvent *e);
protected:
	bool m_bLighted;
	bool m_bMouseIN;
	bool m_bLeftDown;
	QPixmap* m_pHover;
	QPixmap* m_pNormal;
	QPixmap* m_pLighted;
	
};

#endif // CIMAGEBUTTON_H
#include "cimagebutton.h"
#include 
CImageButton::CImageButton(QWidget* pParent):QPushButton(pParent),
	m_bMouseIN(false),
	m_bLeftDown(false),
	m_bLighted(false)
{
}
CImageButton::~CImageButton()
{

}
void CImageButton::SetPixmap(QPixmap* pNormal,QPixmap* pHover,QPixmap* pLighted)
{
	m_pNormal=pNormal;
	m_pHover=pHover;
	m_pLighted=pLighted;
}

void CImageButton::SetLighted(bool value)
{
	if(value != m_bLighted)
	{
		m_bLighted=value;
		repaint();
	}
}

void CImageButton::paintEvent(QPaintEvent* pEvent)
{
	QPixmap* pPixmap;
	if(m_bLighted || m_bLeftDown)
		pPixmap=m_pLighted;
	else
	{
		if(m_bMouseIN)
			pPixmap=m_pHover;
		else
			pPixmap=m_pNormal;
	}
	QPainter painter;
	painter.begin(this);
	if(pPixmap)
		painter.drawPixmap(rect(),*pPixmap);
	if(text().count() > 0)
		painter.drawText(rect(),Qt::AlignCenter,text());
	painter.end();
}

void CImageButton::mousePressEvent(QMouseEvent *e)
{
	if(e->button()==Qt::LeftButton)
	{
		m_bLeftDown=true;
		repaint();
	}
	QPushButton::mousePressEvent(e);
}

void CImageButton::mouseReleaseEvent(QMouseEvent *e)
{
	if(e->button()==Qt::LeftButton)
	{
		m_bLeftDown=false;
		repaint();
	}
	QPushButton::mouseReleaseEvent(e);
}

void CImageButton::enterEvent(QEvent *e)
{
	m_bMouseIN=true;
	repaint();
}

void CImageButton::leaveEvent(QEvent *e)
{
	m_bMouseIN=false;
	repaint();
}
//应用,这样QPushButton形状就是图片的形状
	CImageButton* m_pOrderAbove=new CImageButton(this);
	m_pOrderAbove->SetPixmap(pPixOrderAbove,pPixOrderAbove,pPixOrderAbove);
	m_pOrderAbove->setText(QString::fromLocal8Bit("天亮了"));
	m_pOrderAbove->setStyleSheet("color: rgb(255, 255, 255);");
	m_pOrderAbove->setGeometry(144,0,pPixOrderAbove->width(),pPixOrderAbove->height());




你可能感兴趣的:(QT)