Search code examples
qtqslider

Is there a way to prevent Qt slider dragging beyond a value?


I have implemented the interface where the user is drawing a frame and then moving to next frame which will increment the slider value by 1. User can also increment or decrement the slider value. But, if user has drawn only upto frame 20 then user should not be able to drag slider beyond 20. How can I ensure that?


Solution

  • Use this class and just set setRestrictValue() that is the minimum value that user can drag the slider

    slider.h

    #ifndef SLIDER_H
    #define SLIDER_H
    
    #include <QSlider>
    
    
    class Slider : public QSlider
    {
        Q_OBJECT
    public:
        Slider(QWidget * parent = 0);
        ~Slider();
    
        void setRestrictValue(int value);
    
    private slots:
        void restrictMove(int index);
    
    private:
        int m_restrictValue;
    };
    
    #endif // SLIDER_H
    

    slider.cpp

    #include "slider.h"
    
    Slider::Slider(QWidget *parent) : QSlider(parent)
    {
        connect(this,SIGNAL(valueChanged(int)),this,SLOT(restrictMove(int)));
    
        m_restrictValue = 0;
    }
    
    Slider::~Slider()
    {
    
    }
    
    void Slider::setRestrictValue(int value)
    {
        m_restrictValue = value;
    }
    
    
    void Slider::restrictMove(int index)
    {
        if(index < m_restrictValue)
        {
            this->setSliderPosition(m_restrictValue);
        }
    }
    

    example:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        ui->slider1->setRange(0,100); //slider range
        ui->slider1->setValue(50); //slider current value
        ui->slider1->setRestrictValue(22); //the minimum value that user can drag the slider
    
        ui->slider2->setRange(0,100);//slider range
        ui->slider2->setValue(50); //slider current value
        ui->slider2->setRestrictValue(11);//the minimum value that user can drag the slider
    }