How to always show sign (+ or -) in QDoubleSpinbox?

Viewed 439

If the value in the QDoubleSpinbox is positive, it shows no sign.

enter image description here

If the value is changed to a negative one, it automatically adds the "-" sign.

enter image description here

If the prefix is forced to "+", then the positive numbers will displayed with sign

doubleSB->setPrefix("+");

enter image description here

But the "+" will stay there and won't be automatically removed when the value set is negative

enter image description here

Is there a way to always show the correct sign?

  • "+" sign if the value is positive
  • "-" sign if the value is negative (like it does by default)
1 Answers

A possible solution is to overwrite the textFromValue() method and add that character if necessary:

#include <QApplication>
#include <QDoubleSpinBox>

class DoubleSpinBox: public QDoubleSpinBox
{
public:
    using QDoubleSpinBox::QDoubleSpinBox;
    QString textFromValue(double value) const override
    {
        QString text = QDoubleSpinBox::textFromValue(value);
        if(value > 0)
            text.prepend(QChar('+'));
        return text;
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DoubleSpinBox w;
    w.setMinimum(-100);
    w.setSuffix("%");
    w.show();

    return a.exec();
}
Related