【Qt】实现按钮透明的动画效果
程序员文章站
2022-03-26 19:18:28
...
qt里实现动画一般是用QPropertyAnimation,也支持有透明的动画效果,即属性为opacity。该属性是QWindow类及其派生类才有的,QWidget没有,QWidget及其派生类就用不了,故只能使用其他方法来实现了
我们这里通过QGraphicsOpacityEffect来设置透明度,使用定时器来控制。下面上代码
头文件:
#ifndef RECORDBTN_H
#define RECORDBTN_H
#include <QPushButton>
class QGraphicsOpacityEffect;
class QTimer;
class RecordBtn : public QPushButton
{
Q_OBJECT
public:
explicit RecordBtn(QWidget *parent = 0);
void startAnimation();
void stopAnimation();
bool isActive() const;
signals:
void sigTimeout();
private:
QGraphicsOpacityEffect *m_pOpacityEffect = Q_NULLPTR;
QTimer *m_pTimer = Q_NULLPTR;
bool m_bStatus = false;
float m_opacityVal = 1.0;
};
#endif // RECORDBTN_H
cpp文件:
#include "recordbtn.h"
#include <QGraphicsOpacityEffect>
#include <QTimer>
RecordBtn::RecordBtn(QWidget *parent):
QPushButton(parent)
{
m_pOpacityEffect = new QGraphicsOpacityEffect(this);
this->setGraphicsEffect(m_pOpacityEffect);
m_pTimer = new QTimer(this);
//设置QTimer的高精度
m_pTimer->setTimerType(Qt::PreciseTimer);
connect(m_pTimer, &QTimer::timeout, this, [=](){
emit sigTimeout();
m_pOpacityEffect->setOpacity(m_opacityVal);
if(m_bStatus)
{
m_opacityVal -= 0.1;
}
else
{
m_opacityVal += 0.1;
}
if(m_opacityVal > 0.9)
{
m_bStatus = true;
}
else if(m_opacityVal < 0.1)
{
m_bStatus = false;
}
});
}
void RecordBtn::startAnimation()
{
m_pTimer->start(50);
}
void RecordBtn::stopAnimation()
{
m_pTimer->stop();
m_pOpacityEffect->setOpacity(1.0);
}
bool RecordBtn::isActive() const
{
return m_pTimer->isActive();
}