首先自定义QSlider的子类MyCustomSlider,如下所示。
mycustomslider.h ifndef MYCUSTOMSLIDER_H define MYCUSTOMSLIDER_H include “QSlider” include “QLabel” include “QMouseEvent”class MyCustomSlider : public QSlider
{
public:
MyCustomSlider(QWidget *parent=0);
~MyCustomSlider();protected:
virtual void mousePressEvent(QMouseEvent event);
virtual void mouseReleaseEvent(QMouseEvent event);
virtual void mouseMoveEvent(QMouseEvent *event);private:
QLabel* m_displayLabel;
}; endif // MYCUSTOMSLIDER_Hmycustomslider.cpp
include “mycustomslider.h” include “QPalette”MyCustomSlider::MyCustomSlider(QWidget *parent):QSlider(parent)
{
m_displayLabel=new QLabel(this);
m_displayLabel->setFixedSize(QSize(20,20));
//设置游标背景为白色
m_displayLabel->setAutoFillBackground(true);
QPalette palette;
palette.setColor(QPalette::Background, Qt::white);
m_displayLabel->setPalette(palette);m_displayLabel->setAlignment(Qt::AlignCenter);
m_displayLabel->setVisible(false);
m_displayLabel->move(0,3);
}MyCustomSlider::~MyCustomSlider()
{}
void MyCustomSlider::mousePressEvent(QMouseEvent *event)
{
if(!m_displayLabel->isVisible())
{
m_displayLabel->setVisible(true);
m_displayLabel->setText(QString::number(this->value()));
}
QSlider::mousePressEvent(event);
}void MyCustomSlider::mouseReleaseEvent(QMouseEvent *event)
{
if(m_displayLabel->isVisible())
{
m_displayLabel->setVisible(false);
}
QSlider::mouseReleaseEvent(event);
}void MyCustomSlider::mouseMoveEvent(QMouseEvent event)
{
m_displayLabel->setText(QString::number(this->value()));
m_displayLabel->move((this->width()-m_displayLabel->width())this->value()/(this->maximum()-this->minimum()),3);
QSlider::mouseMoveEvent(event);
}免责声明:文章内容来自互联网,本站不对其真实性负责,也不承担任何法律责任,如有侵权等情况,请与本站联系删除。
转载请注明出处:Qt自定义带游标的slider,在滑块正上方显示当前值 https://www.yhzz.com.cn/a/22101.html