2

I want to enter temperature in my dialog in this format 12°15°

For this i took QDoubleSpinBox widget but wasn't able to set its text like above.

I tried following:

degree_sign= u'\N{DEGREE SIGN}'
temperature = QDOubleSpinBox()
temperature.setSuffix(degree_sign)

and got 12.15°

I think valueFromText() and textFromValue() can help but don't know how to use them.

How to set QDoubleSpinBox text(or value) format like 12°15°?

Patrick
  • 2,464
  • 3
  • 30
  • 47

1 Answers1

0

One way is inherit from QDoubleSpinBox and override the respective methods as follows in this pseudo code:

main.cpp

#include <QDoubleSpinBox>
#include <QApplication>

class MySpinBox : public QDoubleSpinBox
{
    Q_OBJECT
    public:
        explicit MySpinBox(QWidget *parent = 0) : QDoubleSpinBox(parent) {}
    double valueFromText(const QString & text) const
    {
        QString valueText = text;
        valueText.chop(1);
        valueText.replace("°", ".");
        return valueText.toFloat();
    }

    QString textFromValue(double value) const
    {
        QString valueText = QString::number(value);
        valueText.replace(".", "°");
        valueText.append(".");
        return valueText;
    }
};

#include "main.moc"

int main(int argc, char **argv)
{
    QApplication application(argc, argv);
    MySpinBox mySpinBox;
    mySpinBox.show();
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Disclaimer: even though it looks like a compiling code, it does not work, but shows the concept.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • I have converted all code to python except this line `QString valueText = QString::number(value);` I tried to convert this as `valueText = str(value)` but it gives error – Patrick Dec 06 '14 at 18:43
  • I converted code to pyqt but qdoublespinbox shows `0.` – Patrick Dec 06 '14 at 19:03
  • Yes, that is why I marked the answer as pseudo code. The concept is there and you need to fine tune it. – László Papp Dec 06 '14 at 19:05
  • Yes i modified it to get 0°00° `def valueFromText(self, text): valueText = QString() valueText = text valueText.chop(1) valueText.replace(degree_sign,".") return t.toFloat() def textFromValue(self, value): valueText = QString.number(value, format='f', precision=2) valueText.replace(".", degree_sign) valueText.append(degree_sign) return valueText` On clicking up it only increments first value. I am not able to modify second value. Give some hint. Also tell where to learn overriding Qt widgets – Patrick Dec 06 '14 at 19:27
  • @Patrick: please [read the documentation](http://doc-snapshot.qt-project.org/qt5-5.4/qdoublespinbox.html#singleStep-prop). The default step is 1.0, that is why. You need to change that. – László Papp Dec 06 '14 at 20:29
  • agreed default value is 1.0 still i can edit fraction part in QDoubleSpinBox but was not able to edit fraction part in MySpinBox – Patrick Dec 07 '14 at 06:40