自己写的QSlider音量样式,先看样式图:
这是滑块的几个状态。
是直接使用QPaintEvent对其重绘。
代码如下:
#ifndef SLIDER_H
#define SLIDER_H
#include <QWidget>
#include <QSlider>
class Slider : public QSlider
{
Q_OBJECT
public:
explicit Slider(QWidget *parent = nullptr);
void paintEvent(QPaintEvent *ev) override;
void setIcon(QString icon1,QString icon2,QString icon3,QString icon4);
void setDiscoloration(bool dis);
private:
QPixmap m_icon1;
QPixmap m_icon2;
QPixmap m_icon3;
QPixmap m_icon4;
bool m_Discoloration;
};
#endif // SLIDER_H
#include "slider.h"
#include <QPainter>
Slider::Slider(QWidget *parent) : QSlider(parent)
{
//设置默认值
this->setMaximum(100);
this->setMinimum(0);
//进度条是否变色
m_Discoloration = true;
}
void Slider::paintEvent(QPaintEvent *ev)
{
Q_UNUSED(ev)
QPainter painter(this);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
QRect rect = QRect(0, 0, width(), height());
const double k = (double)(value() - minimum()) / (maximum()-minimum());
int x = (int)(rect.width() * k);
QRect fillRect = rect.adjusted(0, 0, x-rect.width(), 0);
QPixmap background_pixmap(":/img/background_pixmap");
//画进度条
p.drawPixmap(rect,background_pixmap);
if(m_Discoloration)
{
if(value() == 100){
p.setPen(QColor(qRgb(253,171,21)));
p.setBrush(QBrush(qRgb(253,171,21)));
p.drawRoundedRect(QRect(0,3,fillRect.width(),fillRect.height()-5),20,20);
p.drawPixmap(QRect(rect.width()-40,(25/2),rect.height()-25,rect.height()-25),m_icon4);
}
else{
if(value() == 0){
p.drawPixmap(QRect(-2,0,rect.height(),rect.height()),m_icon1);
}
p.setPen(QColor(qRgb(52,147,255)));
p.setBrush(QBrush(qRgb(52,147,255)));
if(value()<5 && value()>0)
p.drawRoundedRect(QRect(0,8,fillRect.width(),fillRect.height()-20),20,20);
else if(value()>5)
p.drawRoundedRect(QRect(0,3,fillRect.width(),fillRect.height()-5),20,20);
if(value()>0 && value()<50){
p.drawPixmap(QRect(rect.width()-40,25/2,rect.height()-25,rect.height()-25),m_icon2);
}
else if(value()>50 && value()<100){
p.drawPixmap(QRect(rect.width()-40,25/2,rect.height()-25,rect.height()-25),m_icon3);
}
}
}
else
{
p.setPen(QColor(qRgb(52,147,255)));
p.setBrush(QBrush(qRgb(52,147,255)));
if(value()<5 && value()>0)
p.drawRoundedRect(QRect(0,8,fillRect.width(),fillRect.height()-20),20,20);
else if(value()>= 5)
p.drawRoundedRect(QRect(0,3,fillRect.width(),fillRect.height()-5),20,20);
if(value()>0 && value()<100){
p.drawPixmap(QRect(20,25/2,rect.height()-25,rect.height()-25),m_icon1);
p.drawPixmap(QRect(rect.width()-40,25/2,rect.height()-25,rect.height()-25),m_icon2);
}
else if(value() == 100){
p.drawPixmap(QRect(rect.width()-40,25/2,rect.height()-25,rect.height()-25),m_icon2);
}
}
}
void Slider::setIcon(QString icon1, QString icon2, QString icon3, QString icon4)
{
m_icon1 = icon1;
m_icon2 = icon2;
m_icon3 = icon3;
m_icon4 = icon4;
}
void Slider::setDiscoloration(bool dis)
{
m_Discoloration = dis;
}