3

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.

user12388651
  • 179
  • 1
  • 8
  • 1
    An empty string can be set by means of the [setSpecialValueText](https://doc.qt.io/qt-5/qabstractspinbox.html#specialValueText-prop) method. – Xukrao Feb 11 '20 at 23:19
  • @Xukrao How could I create an event such that when the QSpinBox is not enabled, it will automatically set the value to an empty string? – user12388651 Feb 11 '20 at 23:24

1 Answers1

3

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I don't want to be a heckler, but shouldn't it be the opposite? Enable it when checked, disabled when unchecked. – kalzso Feb 12 '20 at 10:04
  • @kalzso That is a matter of UIX which is irrelevant in this case since the question is not about that subject – eyllanesc Feb 12 '20 at 13:45