我希望水平滑块只有两个值,并且看起来像图片所示。绿色按钮应该是半透明的,即字母将保持在其固定位置,并且当按钮水平移动到任何位置时,文本将可见。
但是到目前为止,我还没有做到这一点。我的代码如下。
头文件。
#ifndef CUSTOMSLIDER_H
#define CUSTOMSLIDER_H
#include <QSlider>
class CustomSlider : public QSlider
{
Q_OBJECT
public:
explicit CustomSlider(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent* aEvent);
QColor m_backgroundColor;
QColor m_color;
QColor m_textColor;
QString m_leftText;
QString m_rightText;
int m_fontSize;
int m_radius;
};
#endif // CUSTOMSLIDER_H
Cpp文件。
#include "CustomSlider.h"
#include <QStylePainter>
#include <QStyleOptionSlider>
CustomSlider::CustomSlider(QWidget *parent):
QSlider(parent),
m_backgroundColor(Qt::gray),
m_color(Qt::green),
m_textColor(Qt::black),
m_leftText("left"),
m_rightText("right"),
m_fontSize(12),
m_radius(10)
{
setFixedSize(140, 40);
setMaximum(1);
setMinimum(0);
setValue(0);
setStyleSheet("QSlider::handle:horizontal {"
"background: rgba(0, 255, 0, 50);"
"border: 0px;"
"width: 70px;"
"height: 40px;"
"border-radius: "+QString::number(m_radius)+"px;"
"}");
}
void CustomSlider::paintEvent(QPaintEvent *aEvent)
{
QStylePainter painter(this);
painter.setPen(Qt::NoPen);
painter.setBrush(m_backgroundColor);
QRect canvas(0, 0, width(), height());
painter.drawRoundedRect(canvas, m_radius, m_radius);
painter.setBrush(m_color);
painter.setPen(QPen(m_textColor, 1));
painter.drawText((canvas.width()/4) - (painter.fontMetrics().width(m_leftText)/2),
canvas.height()/2 + (painter.fontMetrics().height()/4),
m_leftText);
painter.drawText(canvas.right() - (canvas.width()/4) - (painter.fontMetrics().width(m_rightText)/2),
canvas.height()/2 + (painter.fontMetrics().height()/4),
m_rightText);
QStyleOptionSlider opt;
initStyleOption(&opt);
opt.subControls = QStyle::SC_SliderHandle;
painter.drawComplexControl(QStyle::CC_Slider, opt);
}
由于某种原因,背景完全消失,仅按钮显示为半透明的绿色,并且与构造器CustomSlider中样式表中设置的高度和宽度也不相同。
我在做什么错了?