3

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)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Alechan
  • 817
  • 1
  • 10
  • 24

1 Answers1

5

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();
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241