修复在PyQt中输入双打平箱的值

Kak*_*shi 2 python qt pyqt pyqt4

我想创建一个双精度框,以0.2的步长更改值.但是当用户根据步骤输入不正确的值时.我将其标准化为最接近的正确值.我尝试了类似下面显示的代码,但我不知道如何停止输入0.5之类的值.请帮帮我.


    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_()
Run Code Online (Sandbox Code Playgroud)

Ava*_*ris 5

你有两个选择:

  • 您可以继承QSpinBox,覆盖validate方法并使用适当的Q*Validator(例如QRegExpValidator)内部.
  • 您可以valueChanged在使用前检查连接到的插槽中的值,并在必要时进行更正.

由于您已经在使用该valueChanged信号,因此第二个选项应该相当容易实现.只需change_value像这样改变你的方法:

def change_value1(self, val): # new value is passed as an argument
    # so no need for this
    # val = self.spinbox1.value()

    new_val = round(val*5)/5 # one way to fix
    if val != new_val:       # if value is changed, put it in the spinbox
        self.spinbox1.setValue(new_val)

    self.lcd1.display(new_val)
Run Code Online (Sandbox Code Playgroud)

顺便说一下,由于您只使用一个小数精度,因此使用它也是合乎逻辑的:

self.spinbox1.setDecimals(1)
Run Code Online (Sandbox Code Playgroud)

在你的__init__.并尝试使用新风格的信号和插槽.即:

self.connect(self.spinbox1, SIGNAL('valueChanged(double)'), self.change_value1)
Run Code Online (Sandbox Code Playgroud)

可以写成:

self.spinbox1.valueChanged[float].connect(self.change_value1)
Run Code Online (Sandbox Code Playgroud)

编辑

子类:

class MySpinBox(QDoubleSpinBox):
    def __init__(self, parent=None):
        super(MySpinBox, self).__init__(parent)
        # any RegExp that matches the allowed input
        self.validator = QRegExpValidator(QRegExp("\\d+[\\.]{0,1}[02468]{0,1}"), self)

    def validate(self, text, pos):
        # this decides if the entered value should be accepted
        return self.validator.validate(text, pos)
Run Code Online (Sandbox Code Playgroud)

然后使用而不是使用QDoubleSpinBox你将MySpinBox输入检查留给这个类.