6

Regarding some task I must do the following. Consider I have a QDoubleSpinBox with positive values from 0 to 1000. And every time when user tries to lower the value of spinbox, f.e. to click the down button when value is 0, the value of spinbox must be string "unset". I tried to do this, to clear the value of spinbox and then setPrefix. But it did not worked. Any other solutions?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 1
    Hm, but QDoubleSpinBox is to display floating point numbers. However you want to set a string? Maybe using a label along with the spin box would be better idea? – vahancho Nov 14 '14 at 08:24

3 Answers3

11

You can try specialValueText.

This is a example:

#include <QApplication>
#include <QDoubleSpinBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QDoubleSpinBox doubleSpinBox;
    doubleSpinBox.setRange(0.f, 1000.f);
    doubleSpinBox.setValue(1.f);
    doubleSpinBox.setSpecialValueText("unset");

    doubleSpinBox.show();
    return a.exec();
}

when value is 0, the value of spinbox must be string "unset".

pezy
  • 1,022
  • 2
  • 8
  • 27
  • 2
    Nice functionality: Using Qt quite a while and never thought something like this exists. Thanks for your tip! – Robert Nov 14 '14 at 08:47
  • For those wondering, to unset this just call doubleSpinBox.setSpecialValueText("") – nicolaum Sep 02 '23 at 11:55
6

There are two solutions to achieve what you want.

As pezy in the other answer says using setSpecialValueText where the text is shown when the current value() == minimum() of the spinbox

or a bit more powerful: subclass QSpinBox and override following functions:

int valueFromText(const QString &text) const;
QString textFromValue(int value) const;
QValidator::State validate(QString & input, int & pos) const;

Have a look here, trying something similar QSpinBox enter NaN as a valid value.

Community
  • 1
  • 1
Robert
  • 1,235
  • 7
  • 17
-1

Sub class QSpinBox and define your behavior.
Take a look at this example

Pratham
  • 1,522
  • 1
  • 18
  • 33