QT自定义指示灯(可闪烁、可移动)
立即下载
资源介绍:
QT实现指示灯控件。一般有2种形式:1、使用QPixmap绘制指示灯;2、在paintEvent中使用QPainter来绘制。本示例对这两种形式做了封装,实现了两种不同的指示灯。都可闪烁、可移动。
#include "roundlamp.h"
RoundLamp::RoundLamp(QWidget *parent) : Lamp(parent)
{
setFixedSize(50,50);
m_onColor=QColor("green");
m_offColor=QColor(125,125,125);
setTickTime(m_tickTime);
}
RoundLamp::~RoundLamp()
{
}
void RoundLamp::upFrameOut(QPainter *p,int r)
{
p->save();
QLinearGradient gradient(0,-r,0,r);
gradient.setColorAt(1,QColor(166,166,166));
gradient.setColorAt(0,QColor(255,255,255));
gradient.setSpread(QGradient::PadSpread);
p->setBrush(gradient);
p->drawEllipse(-r,-r,2*r,2*r);
p->restore();
update();
}
void RoundLamp::upFrameIn(QPainter *p, int r)
{
p->save();
QLinearGradient gradient(0,-r,0,r);
gradient.setColorAt(0,QColor(166,166,166));
gradient.setColorAt(1,QColor(255,255,255));
gradient.setSpread(QGradient::PadSpread);
p->setBrush(gradient);
p->drawEllipse(-r,-r,2*r,2*r);
p->restore();
update();
}
void RoundLamp::upLampColor(QPainter *p,int r)
{
p->save();
if(m_state)
{
if(m_canTick)
{
if(m_tickState) p->setBrush(m_onColor);
else p->setBrush(m_offColor);
}
else p->setBrush(m_onColor);
}
else p->setBrush(m_offColor);
p->drawEllipse(-r,-r,2*r,2*r);
p->restore();
update();
}
void RoundLamp::setTickTime(int tickTime)
{
m_tickTimer.setInterval(tickTime);
connect(&m_tickTimer,&QTimer::timeout,this,[this]{
if(m_tickState)
m_tickState=false;
else
m_tickState=true;
});
}
void RoundLamp::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
int width=this->width();
int height=this->height();
int side=qMin(width,height);
QPainter p(this);
p.translate(width/2,height/2);
p.scale(side/200.0,side/200.0);
p.setPen(Qt::NoPen);
if(m_canTick&&(!m_tickTimer.isActive()))
m_tickTimer.start(m_tickTime);
else if(!m_canTick&&m_tickTimer.isActive())
m_tickTimer.stop();
upFrameOut(&p,99);
upFrameIn(&p,90);
upLampColor(&p,80);
upText(&p);
}
void RoundLamp::setOnColor(QColor onColor)
{
m_onColor = onColor;
update();
}