Loading...
打赏
Qt自定义带游标的slider,在滑块正上方显示当前值
big_anana 发布于 2017/11/23 浏览 1317 点赞 0 收藏 0

首先自定义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);
}

*本文仅代表作者观点,不代表易百纳技术社区立场。系作者授权易百纳技术社区发表,未经许可不得转载。

编辑 删除

精彩评论

内容存在敏感词
打赏作者
big_anana
您的支持将鼓励我继续创作!
金额:
¥1 ¥5 ¥10 ¥50 ¥100
支付方式:
微信支付
支付宝支付
微信支付
打赏成功!

感谢您的打赏,如若您也想被打赏,可前往 发表专栏 哦~

易百纳技术社区
确定要删除此文章、专栏、评论吗?
确定
取消
易百纳技术社区