对 QSlider 使用浮点数

2022-01-12 00:00:00 python pyqt pyqt5 pyqt4 qslider

问题描述

我有一个 QLineEdit 和一个 QSlider,它们在其中相互交互.

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

例如.如果我在 QLineEdit 中设置了一个值,则滑块将被更新,或者如果我将滑块滑过,它将更新 QLineEdit 中的值

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

# If user change value on the slider
self.timer_slider.valueChanged.connect(self.set_value)
# If user sets a value in the text box instead
self.timer_value.textChanged.connect(self.set_slider)

def set_slider(self, value):
    self.timer_slider.setValue(int(value))

def set_value(self, value):
    self.timer_value.setText(str(value))

无论如何我可以使用 float 代替 int 值吗?

Is there anyway that I can use float instead of int values?


解决方案

@dissidia 的回答很好.但是,如果您的应用程序中有很多滑块,或者如果您需要几个不同的比例因子,则将 QSlider 子类化以制作您自己的 QDoubleSlider 是值得的.

@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.

下面的类基于其他人的工作,但如果你链接到 QLineEdit 或 QDoubleSpinBox,你会想要一个额外的功能:一个新的 valueChanged 信号,称为 doubleValueChanged.

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))

相关文章