Use float for QSlider

前端 未结 3 1019
轻奢々
轻奢々 2021-01-07 01:05

I have a QLineEdit and a QSlider in which it interacts with each other.

Eg. If I set a value in the QLineEdit, the slider will be updated, or if I slide the slider a

3条回答
  •  离开以前
    2021-01-07 01:22

    @dissidia's answer is good. But if you have a lot of sliders in your app or if you need several different scale factors, it pays to subclass QSlider to make your own QDoubleSlider.

    The class below is based on the work of others, but has an extra feature you'll want if you link to a QLineEdit or QDoubleSpinBox: a new signal for valueChanged called doubleValueChanged.

    class DoubleSlider(QSlider):
    
        # create our our signal that we can connect to if necessary
        doubleValueChanged = pyqtSignal(float)
    
        def __init__(self, decimals=3, *args, **kargs):
            super(DoubleSlider, self).__init__( *args, **kargs)
            self._multi = 10 ** decimals
    
            self.valueChanged.connect(self.emitDoubleValueChanged)
    
        def emitDoubleValueChanged(self):
            value = float(super(DoubleSlider, self).value())/self._multi
            self.doubleValueChanged.emit(value)
    
        def value(self):
            return float(super(DoubleSlider, self).value()) / self._multi
    
        def setMinimum(self, value):
            return super(DoubleSlider, self).setMinimum(value * self._multi)
    
        def setMaximum(self, value):
            return super(DoubleSlider, self).setMaximum(value * self._multi)
    
        def setSingleStep(self, value):
            return super(DoubleSlider, self).setSingleStep(value * self._multi)
    
        def singleStep(self):
            return float(super(DoubleSlider, self).singleStep()) / self._multi
    
        def setValue(self, value):
            super(DoubleSlider, self).setValue(int(value * self._multi))
    

提交回复
热议问题