首先自定义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_H
mycustomslider.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);
- }
然后将界面QSlider控件提升为MyCustomSlider,提升方法如下所示。
最后的效果如下图所示,当鼠标点击滑块或者拖动滑块时,滑块正上方的游标实时显示当前值,松开鼠标时,游标隐藏。
源码链接:见http://blog.csdn.net/caoshangpa/article/details/51973902的评论
http://blog.csdn.net/caoshangpa/article/details/51973902