Andrei Cioara
Andrei Cioara

Reputation: 3664

Qt QSpinBox with a set of predefined values

I have a QSpinBox which should only accept a set of discrete values (let's say 2, 5, 10). I can setMinimum(2) and setMaximum(10), but I cannot setSingleStep because I have a step of 3 and one of 5.

Is there a different widget which I can use, but which has the same UI as the QSpinBox?

If not, what should I overwrite to achieve the desired effect?

Upvotes: 3

Views: 1545

Answers (1)

Dimitry Ernot
Dimitry Ernot

Reputation: 6584

Use QSpinBox::stepsBy() to handle the values.

For example:

class Spinbox: public QSpinBox
{
public:
    Spinbox(): QSpinBox()
    {
        acceptedValues << 0 << 3 << 5 << 10; // We want only 0, 3, 5, and 10
        setRange(acceptedValues.first(), acceptedValues.last());

    }
    virtual void stepBy(int steps) override
    {
        int const index = std::max(0, (acceptedValues.indexOf(value()) + steps) % acceptedValues.length()); // Bounds the index between 0 and length
        setValue(acceptedValues.value(index));
    }
private:
    QList<int> acceptedValues;
};

Upvotes: 3

Related Questions