qt下的三态按钮 下载本文

内容发布更新时间 : 2024/12/23 18:43:30星期一 下面是文章的全部内容请认真阅读。

#include

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 \

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(\QIcon(\ button->show(); return app.exec(); }