Set QDoubleSpinBox value to an empty string, when not enabled

1.7k views Asked by At

If I have a QDoubleSpinBox and have a method available called setEnabled which takes a boolean value. If this value is set to False, the QDoubleSpinBox will appear greyed, showing the number inside the Spin Button, but not allowing the user to type anything or interact with it. I would like a slight modification, such that when the QDoubleSpinBox is not enabled, I would like the Spin Button value to be set to an empty string or not rendered, and remove any previous value from being shown.

1

There are 1 answers

2
eyllanesc On BEST ANSWER

One possible solution is to show and hide the QLineEdit of the QDoubleSpinBox if the QDoubleSpinBox is enabled or disabled, respectively. To detect the change of state of the enabled property, you must override the changeEvent() method and verify the QEvent::EnabledChange event:

import sys

from PyQt5 import QtCore, QtWidgets


class DoubleSpinBox(QtWidgets.QDoubleSpinBox):
    def changeEvent(self, e):
        if e.type() == QtCore.QEvent.EnabledChange:
            self.lineEdit().setVisible(self.isEnabled())
        return super().changeEvent(e)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    radiobutton = QtWidgets.QRadioButton("enabled/disabled")
    spinbox = DoubleSpinBox()
    radiobutton.toggled.connect(spinbox.setDisabled)

    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)
    lay.addWidget(radiobutton)
    lay.addWidget(spinbox)
    w.show()

    sys.exit(app.exec_())

enter image description here

enter image description here