How to add a hover transition to QPushButton?

前端 未结 2 1152
情歌与酒
情歌与酒 2021-01-06 17:31

I try to make a custom QPushButton with a stylesheet. I want to custom color of button when we mouse over it. It works, but I want to put a transition duration.

2条回答
  •  渐次进展
    2021-01-06 17:57

    You can use Animation.

    MyButton.h

    #include 
    #include 
    #include 
    
    class MyButton : public QPushButton
    {
        Q_OBJECT
        Q_PROPERTY(QColor color READ GetColor WRITE SetColor)
    
    public:
        explicit MyButton(QWidget *parent = 0);
    
        void SetColor(const QColor& color);
        const QColor& GetColor() const;
    
    protected:
        bool eventFilter(QObject *obj, QEvent *e);
    
    private:
        QColor m_currentColor;
    
        QPropertyAnimation m_colorAnimation;
    
        void StartHoverEnterAnimation();
        void StartHoverLeaveAnimation();
    };
    

    MyButton.cpp

    #include "MyButton.h"
    
    #include 
    #include 
    
    MyButton::MyButton(QWidget *parent) :
        QPushButton(parent),
        m_colorAnimation(this, "color")
    {
        this->installEventFilter(this);
    }
    
    void MyButton::SetColor(const QColor& color)
    {
        m_currentColor = color;
        QString css = "QPushButton { border-radius: 5px; ";
        css.append("border: 1.5px solid rgb(91,231,255); ");
        QString strColor = QString("rgb(%1, %2, %3)").arg(color.red()).arg(color.green()).arg(color.blue());
        css.append("background-color: " + strColor + "; }");
        setStyleSheet(css);
    }
    
    const QColor& MyButton::GetColor() const
    {
        return m_currentColor;
    }
    
    bool MyButton::eventFilter(QObject *obj, QEvent *e)
    {
        if (e->type() == QEvent::HoverEnter) {
            StartHoverEnterAnimation();
        }
    
        if (e->type() == QEvent::HoverLeave) {
            StartHoverLeaveAnimation();
        }
    
        return false;
    }
    
    void MyButton::StartHoverEnterAnimation()
    {
        m_colorAnimation.stop();
    
        m_colorAnimation.setDuration(900); //set your transition
        m_colorAnimation.setStartValue(GetColor()); //starts from current color
        m_colorAnimation.setEndValue(QColor(100, 100, 100));//set your hover color
    
        m_colorAnimation.setEasingCurve(QEasingCurve::Linear);//animation style
    
        m_colorAnimation.start();
    }
    
    void MyButton::StartHoverLeaveAnimation()
    {
        m_colorAnimation.stop();
    
        m_colorAnimation.setDuration(900); //set your transition
        m_colorAnimation.setStartValue(GetColor()); //starts from current color
        m_colorAnimation.setEndValue(QColor(255, 0, 0));//set your regular color
    
        m_colorAnimation.setEasingCurve(QEasingCurve::Linear);//animation style
    
        m_colorAnimation.start();
    }
    

    It will conflict with external qss setting. So set all qss in SetColor.

提交回复
热议问题