QT:三态按钮

三态按钮(普通态,鼠标停留态,点击态)在设计炫丽界时是很常用的一项功能,但QT并没有直接支持这个功能,只好自己写一个了,通过继承QToolButton实现。


上代码:

#include <QtGui>

class CoolButton : public QToolButton
{
	Q_OBJECT
private:
	QIcon m_NormalIcon;
	QIcon m_FocusIcon;
	QIcon m_PressedIcon;
protected:
	void enterEvent(QEvent *event);
	void leaveEvent(QEvent *event);
	void mousePressEvent(QMouseEvent *event);
	void mouseReleaseEvent(QMouseEvent *event);
public:
	CoolButton(QWidget *parent = 0);
	virtual ~CoolButton();
	void SetButtonIcons(const QIcon &normal, 
		const QIcon &focus = QIcon(),
		const QIcon &pressed = QIcon() );
};

CoolButton::CoolButton(QWidget *parent)
: QToolButton(parent)
{
	//为了让图标看起来自然一点而设置了这两个操作
	setDown(false);
	setFocusPolicy(Qt::NoFocus);
}

CoolButton::~CoolButton()
{

}

//重载“进入”和“离开”事件,进入时切换为另一个图标,离开时还原
void CoolButton::enterEvent(QEvent *event)
{
	if( isEnabled() && !m_FocusIcon.isNull() )
		setIcon(m_FocusIcon);
}

void CoolButton::leaveEvent(QEvent *event)
{
	if( isEnabled() )
		setIcon(m_NormalIcon);
}

//重载鼠标事件
void CoolButton::mousePressEvent(QMouseEvent *event)
{
	if( isEnabled() && !m_PressedIcon.isNull() )
		setIcon(m_PressedIcon);
	QToolButton::mousePressEvent(event);
}

void CoolButton::mouseReleaseEvent(QMouseEvent *event)
{
	if( isEnabled() && m_FocusIcon.isNull() )
		setIcon(m_FocusIcon);
	QToolButton::mouseReleaseEvent(event);
}

void CoolButton::SetButtonIcons(const QIcon &normal, 
	const QIcon &focus, const QIcon &pressed)
{
	m_NormalIcon = normal;
	m_FocusIcon = focus;
	m_PressedIcon = pressed;
	setIcon(m_NormalIcon);
}

#include "main.moc"

int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	CoolButton *button = new CoolButton;
	//QObject::connect(button, SIGNAL(clicked()), qApp, SLOT(quit()));
	button->setIconSize(QSize(40, 40));
	button->SetButtonIcons(QIcon("normal.png"), QIcon("focus.png"), QIcon("pressed.png"));
	button->show();
	return app.exec();
}

你可能感兴趣的:(qt,button,Signal)