Qt——仿bilibili直播的调音量控件

时间:2022-02-27 19:57:51

Qt——仿bilibili直播的调音量控件

Qt——仿bilibili直播的调音量控件


.h

/////////////////////////////////////////////////////////
//BIG_C_GOD
/////////////////////////////////////////////////////////
class VolumeController : public QWidget
{
Q_OBJECT
public:
explicit VolumeController(QWidget *parent = 0);

void setMaxValue(int value);
protected:
int m_maxValue;
int m_value;
int m_mouseCurPos;
int m_isPress;

void mousePressEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
void leaveEvent(QEvent *);
void paintEvent(QPaintEvent *);

signals:
void valueChange(int value);
};



.cpp

VolumeController::VolumeController(QWidget *parent) :
QWidget(parent),m_maxValue(100),m_value(0),m_mouseCurPos(0),m_isPress(0)
{
setMouseTracking(true);//在任何情况下启用mouseMoveEvent
}

void VolumeController::setMaxValue(int value)
{
m_maxValue = value;
}

void VolumeController::mousePressEvent(QMouseEvent *e)
{
m_isPress = 1;

if(e->pos().x() >= 0 && e->pos().x() <= width())
{
m_mouseCurPos = e->pos().x();
m_value = e->pos().x();
}

emit valueChange(m_value*m_maxValue/width());

update();
}

void VolumeController::mouseMoveEvent(QMouseEvent *e)
{
if(e->pos().x() >= 0 && e->pos().x() <= width())
{
//鼠标滑过生效
m_mouseCurPos = e->pos().x();

//鼠标按下生效
if(m_isPress)
m_value = e->pos().x();
}

emit valueChange(m_value*m_maxValue/width());

update();
}

void VolumeController::mouseReleaseEvent(QMouseEvent *)
{
m_isPress = 0;
}

void VolumeController::leaveEvent(QEvent *)
{
m_mouseCurPos = 0;

update();
}

void VolumeController::paintEvent(QPaintEvent *)
{
QPainter painter;

painter.begin(this);
painter.fillRect(rect(),QColor(0,0,0,100));
painter.end();

QImage mask(width(),height(),QImage::Format_ARGB32);
painter.begin(&mask);
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(0,0,0));
mask.fill(QColor(255,255,255,0));

int scaling_flag = m_mouseCurPos*10/width();//找出鼠标悬停的位置

for(int i = 0; i < 10; ++i)
if(i == scaling_flag)
{
double parameter = qAbs(width()/20 - m_mouseCurPos%(width()/10))/(double)width()*20;//参数为0时最大
painter.drawRoundedRect(QRect(width()/10*i + width()/40,parameter*height()/5,
width()/20,height() - parameter*height()/5),
width()/20,width()/20);
}
else
painter.drawRoundedRect(QRect(width()/10*i + width()/40,height()/5,width()/20,height()/5*4),
width()/20,width()/20);
painter.end();

painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QRegion region(QBitmap::fromImage(mask));
painter.setClipRegion(region);

painter.fillRect(QRect(0,0,width(),height()),QColor(255,255,255));
painter.fillRect(QRect(0,0,m_value,height()),QColor(242,156,177));
painter.end();
}