QSlider show min, max and current value
Asked Answered
S

3

10

Is it possible to show minimum, maximum and current selected value of QSlider? Of course I can use labels to display this, but I think there must be such possibility in QSlider

Sholem answered 22/8, 2013 at 14:52 Comment(1)
I think you will have to subclass it.Gunboat
M
11

You have two options..

1) as being mentioned in comments - sub - class

2) add as many QLabel's as you like with QSlider as a parent, install eventHandler() on QSlider to catch resize event to proper position them, and obviously handle scroll events, so you can update them... So labels will just float on top of QSlider

Mastoid answered 22/8, 2013 at 15:26 Comment(0)
S
10

Here is my quick implementation of a fancy slider which subclass qslider to displays the current value just below the slider handle into a tooltip.

Header

#ifndef FANCYSLIDER_H
#define FANCYSLIDER_H

#include <QSlider>

class FancySlider : public QSlider
{
    Q_OBJECT
public:
    explicit FancySlider(QWidget *parent = 0);
    explicit FancySlider(Qt::Orientation orientation, QWidget *parent = 0);

protected:
    virtual void sliderChange(SliderChange change);
};

#endif // FANCYSLIDER_H

Cpp

#include "FancySlider.h"

#include <QStyleOptionSlider>
#include <QToolTip>

FancySlider::FancySlider(QWidget * parent)
    : QSlider(parent)
{
}

FancySlider::FancySlider(Qt::Orientation orientation, QWidget * parent)
    : QSlider(orientation, parent)
{
}

void FancySlider::sliderChange(QAbstractSlider::SliderChange change)
{
    QSlider::sliderChange(change);

    if (change == QAbstractSlider::SliderValueChange )
    {
        QStyleOptionSlider opt;
        initStyleOption(&opt);

        QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
        QPoint bottomRightCorner = sr.bottomLeft();

        QToolTip::showText(mapToGlobal( QPoint( bottomRightCorner.x(), bottomRightCorner.y() ) ), QString::number(value()), this);
    }
}
Seneca answered 10/2, 2017 at 13:17 Comment(0)
I
3

Here is my implementation, without subclassing. Instanciate a slider with a label at right, showing the current value of slider :

QWidget *tmpW1 = new QWidget(this);
QHBoxLayout *tmpH1 = new QHBoxLayout(this);
QLabel *tmpLabel = new QLabel("0");

QSlider *tmpSlider = new QSlider(Qt::Horizontal, this);
tmpSlider->setMinimum(0);
tmpSlider->setMaximum(10);
tmpSlider->setValue(5);

tmpH1->addWidget(tmpSlider);
tmpH1->addWidget(tmpLabel);
tmpW1->setLayout(tmpH1);

QObject::connect(tmpSlider, &QSlider::valueChanged, this, [=] () {
    tmpLabel->setText(QString::number(tmpSlider->value()));
});
Iterative answered 2/1, 2020 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.