I want to create a doublespin box that changes values in steps of 0.2. But when the user enters a value that is not correct according to the steps. I normalizes that to the nearest correct value.
I tried something like the code shown below but I don’t know how to stop values like 0.5 to be entered. Please help me on this.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class SigSlot(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setWindowTitle('spinbox value')
self.resize(250,150)
self.lcd1 = QLCDNumber(self)
self.spinbox1 = QDoubleSpinBox(self)
self.spinbox1.setSingleStep(0.2)
self.spinbox1.setCorrectionMode(1)
# create a Grid Layout
grid = QGridLayout()
grid.addWidget(self.lcd1, 0, 0)
grid.addWidget(self.spinbox1, 1, 0)
self.setLayout(grid)
# allows access to the spinbox value as it changes
self.connect(self.spinbox1, SIGNAL('valueChanged(double)'), self.change_value1)
def change_value1(self, event):
val = self.spinbox1.value()
self.lcd1.display(val)
app = QApplication([])
qb = SigSlot()
qb.show()
app.exec_()
You have two choices:
QSpinBox, overridevalidatemethod and use an appropriateQ*Validator(e.g.QRegExpValidator) inside.valueChangedbefore using and correct it if necessary.Since you are already using the
valueChangedsignal, second option should be fairly easy to implement. Just change yourchange_valuemethod like this:By the way, since you are using only one decimal precision, it might be logical to also use:
in your
__init__. And try to use the new style signals and slots. i.e.:could be written as:
Edit
Subclassing:
then instead of using
QDoubleSpinBoxyou would useMySpinBoxand leave the input checking to this class.