Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to user input an infinity value to a QDoubleSpinBox?

I'm trying to set up a QDoubleSpinBox in Python 3.7 with PyQt5, that can take a range of values from -np.inf to np.inf. I would also like the user to set the values to either of those, -np.inf or np.inf. How would I/the user do that?

After adjusting the minimum and maximum of the QDoubleSpinBox it is possible to set the value in code and either "-inf" or "inf" shows up in the displayed box.

from PyQt5.QtWidgets import QDoubleSpinBox

[...]

dsbTest = QDoubleSpinBox()

# first set the desired range 
dsbTest.setRange(-np.inf, np.inf)

# set the value to positive infinity, successfully
dsbTest.setValue(np.inf)

However, after changing it to any other value, let's say 5, I find myself unable to enter "-inf" or "inf" back into the GUI.

When I type "i" or "inf", no input is taken, by which I mean, the displayed current value does not change from 5.

like image 910
andreas Avatar asked Oct 30 '25 14:10

andreas


1 Answers

I ended up doing it like this, making a subclass.

class InftyDoubleSpinBox(QDoubleSpinBox):

    def __init__(self):
        super(QDoubleSpinBox, self).__init__()

        self.setMinimum(-np.inf)
        self.setMaximum(np.inf)

    def keyPressEvent(self, e: QtGui.QKeyEvent):

        if e.key() == QtCore.Qt.Key_Home:
            self.setValue(self.maximum())
        elif e.key() == QtCore.Qt.Key_End:
            self.setValue(self.minimum())
        else:
            super(QDoubleSpinBox, self).keyPressEvent(e)

I set minimum and maximum at the beginning to -np.inf, np.inf. In the keyPressEvent Home and End Buttons will be caught, to set the value to minimum or maximum.

For any other key, the QDoubleSpinBox will react as usual, as the base function is called.

This also works for other assigned min/max values after init() is called. Which was desirable for my case.

like image 57
andreas Avatar answered Nov 02 '25 04:11

andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!