QDoubleSpinBox which accept dots and also commas as a decimal separator

1.1k Views Asked by At

I need a spinbox which accept dots and also commas as a decimal separator.

I've changed the Locale settings: self.setLocale(QLocale(QLocale.C))

Because of that, my spinbox accept a dot as a decimal separator. A comma also shows up on screen when the comma button is pressed, but it disappears after editing.

I've redefined the keyPressEvent. Now, when I use the comma button, it simulates the dot key and calls the original keyPressEvent of the QDoubleSpinBox. But nothing happens on the spinbox screen, and I don't know what I missed.

Does anyone see the problem?

class MyDoubleSpinBox(QDoubleSpinBox):

    def __init__(self):

        super().__init__()

        self.setValue(0.00)
        self.setSingleStep(0.01)
        self.setMaximum(1000)

    def keyPressEvent(self, in_event):  # 46 = dot; 44 = comma:
        if in_event.key() == 44:
            self.keyPressEvent(QKeyEvent(QEvent.KeyPress, 46, Qt.NoModifier, 0, 0, 0))

        else:
            print(in_event.key()) # it's working (46 even if I press comma)
            QDoubleSpinBox.keyPressEvent(self, in_event)
1

There are 1 best solutions below

1
kpsylock On

You should override validate() and valueFromText() methods instead, see https://stackoverflow.com/a/72054836/12108865