Reputation: 23
Suppose I want a QSpinBox
to have valid values from 0 to 10 with a step of 2 (i.e., 0, 2, 4, 6, 8, 10).
I can set the QSpinBox
to have minimum of 0 and maximum of 10, with a singleStep of 2. If users click the up/down arrows, it works well. However, if user type in an odd number (say 3), the spinbox still think it is valid and accepts it.
Whatelse should I do so that my QSpinBox will not allow odd numbers in this case?
Upvotes: 2
Views: 2224
Reputation: 244301
To correct this problem you can implement the valueChanged signal, verify if the value is correct, if it is not modicas nothing, in contrast if not, you place the previous value.
Example:
import sys
from PyQt4.QtCore import pyqtSignal
from PyQt4.QtGui import QApplication, QSpinBox
class SpinBox(QSpinBox):
# Replaces the valueChanged signal
newValueChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(SpinBox, self).__init__(parent=parent)
self.valueChanged.connect(self.onValueChanged)
self.before_value = self.value()
self.newValueChanged.connect(self.slot)
def onValueChanged(self, i):
if not self.isValid(i):
self.setValue(self.before_value)
else:
self.newValueChanged.emit(i)
self.before_value = i
def isValid(self, value):
if (self.minimum() - value % self.singleStep()) == 0:
return True
return False
def slot(self, value):
print(value)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = SpinBox()
w.setMinimum(0)
w.setMaximum(10)
w.setSingleStep(2)
w.show()
sys.exit(app.exec_())
Upvotes: 2