9

I have a QSpinBox in which I want to enable the arrows (for up and down values) but disable inserting data by the user. I've tried using this:

QtGui.QSpinBox.setReadOnly(True)

But it doesn't work. All is disabled and the arrows are 'stuck'.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
roy.me
  • 421
  • 2
  • 7
  • 19

3 Answers3

13

If you set the spin-box readonly, it will disable eveything. Instead, just set the line-edit readonly, and then buttons will still work:

spinbox.lineEdit().setReadOnly(True)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
4

you can block spinboxes editor by QtGui.QSpinBox.lineEdit().setEnabled(False).

edit: and set font color and background-color:

spinbox.lineEdit().setStyleSheet('color: black; background-color: white;')
a_manthey_67
  • 4,046
  • 1
  • 17
  • 28
  • Thx, it works. Any idea how do I change the font color? It greys out the spinbox background and the font. I tried this: QtGui.QSpinBox.setStyleSheet("color: rgb(161,161,161); ") but still the font is grey – roy.me Sep 08 '16 at 14:13
  • i think, the solution of @ekhumoro has some advantages: 'setStyleSheet' is not necessary, the user can copy the value to clipboard and no cursor is shown when 'readOnly' is set to True – a_manthey_67 Sep 09 '16 at 10:19
  • The color black and background color-white does not seem to work... any idea? – roy.me Sep 11 '16 at 14:13
2

In case someone looking for an answer for this problem in C++ come here (like me), the other answers are not straightforward because QSpinBox::lineEdit() is a protected member (so it would require to also extend the class).

What worked for me was:

    auto l1SpinBox = new QSpinBox(this);
    auto lineEdit = l1SpinBox->findChild<QLineEdit*>();
    lineEdit->setReadOnly(true);
    lineEdit->setFocusPolicy(Qt::NoFocus);
    connect(l1SpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), l1SpinBox,
            [&, lineEdit](){lineEdit->deselect();}, Qt::QueuedConnection);

setReadOnly alone may do the trick for you. However in my case, I wanted to improve UI making it also not focusable, and then hiding the selection when the value changes.

Adriel Jr
  • 2,451
  • 19
  • 25