如何确定QSlider的移动方向?

时间:2017-09-28 12:35:36

标签: python pyqt pyqt5 qslider

有没有办法让Qt 5.9中的QSlider移动?

对于上下文,我正在制作一个GUI,用户可以在总和低于1的条件下调整一些滑块。

滑块在彼此上方,如果您移动下滑块中的一个,则上面的滑块不会移动。但是,下面的人会这样做。

对于最后一个滑块,用户应该能够向上移动它,但是应该允许它向下移动。

事先,谢谢:)

1 个答案:

答案 0 :(得分:1)

QSlider没有那个属性,所以最合理的是使用存储前一个位置的逻辑创建一个类,在下面的类中我实现了这个逻辑,我还添加了一个信号来异步通知你:

class Slider(QSlider):
    Nothing, Forward, Backward = range(3)
    directionChanged = pyqtSignal(int)
    def __init__(self, parent=None):
        QSlider.__init__(self, parent)
        self._direction = Slider.Nothing
        self.last = self.value()/self.maximum()
        self.valueChanged.connect(self.onValueChanged)

    def onValueChanged(self, value):
        current = value/self.maximum()
        direction = Slider.Forward if self.last < current else Slider.Backward
        if self._direction != direction:
            self.directionChanged.emit(direction)
            self._direction = direction
        self.last = current

    def direction(self):
        return self._direction

在以下部分中,有一个使用此类的示例:

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setLayout(QVBoxLayout())
        slider = Slider(self)
        slider.setOrientation(Qt.Horizontal)
        self.layout().addWidget(slider)
        slider.directionChanged.connect(self.onDirectionChanged)
        slider.valueChanged.connect(self.onValueChanged)

    def onDirectionChanged(self, direction):
        if direction == Slider.Forward:
            print("Forward")
        elif direction == Slider.Backward:
            print("Backward")

    def onValueChanged(self, value):
        dirstr = "Forward" if self.sender().direction() == Slider.Forward else "Backward"
        print(value, dirstr)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
相关问题