Search code examples
qtqwidgetqspinbox

QDoubleSpinBox with leading zeros (always 4 digits)


I have a QDoubleSpinBox in range 0-7000, but want the value always displayed as 4 digits (0-> 0000, 1 -> 0001 , 30 -> 0030, 3333 -> 3333).

I understand I can add a prefix, but a prefix is always added. What are my options?


Solution

  • If you use integers, then QSpinBox will be enough.

    You can simply inherit from QSpinBox and re-implement the textFromValue function:

    class MySpinBox: public QSpinBox 
    {
        Q_OBJECT
    
    public:
        MySpinBox( QWidget * parent = 0) :
            QSpinBox(parent)
        {
        }
    
        virtual QString textFromValue ( int value ) const
        {
            /* 4 - number of digits, 10 - base of number, '0' - pad character*/
            return QString("%1").arg(value, 4 , 10, QChar('0'));
        }
    };
    

    Filling QString this way does the trick.