Qt QSpinBox带有一组预定义值

问题描述 投票:3回答:1

我有一个QSpinBox,它应该只接受一组离散值(让我们说2,5,10)。我可以setMinimum(2)setMaximum(10),但我不能setSingleStep因为我有一步3和5之一。

是否有一个我可以使用的不同小部件,但它与QSpinBox具有相同的UI?

如果没有,我应该覆盖什么以达到预期的效果?

qt qspinbox
1个回答
3
投票

使用QSpinBox::stepsBy()来处理这些值。

例如:

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.