cLupus
cLupus

Reputation: 563

How do I determine what direction a QSlider is being moved?

Is there a way to get the direction that a QSlider in Qt 5.9 is moving?

For context, I am making a GUI in which the user can adjust some sliders, under the condition that the total sum is below 1.

The sliders are above each other, and if you move one of the lower slider, those above does not move. Those below, however, do.

For the last slider, the user should not be able to move it upward, but should be allowed to move it downward.

In advance, thanks :)

Upvotes: 1

Views: 1747

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

QSlider does not have that property, so the most reasonable thing is to create a class using the logic of having stored the previous position, in the following class I have implemented this logic, I have also added a signal to notify you asynchronously:

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

In the following part there is an example of the use of this class:

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

Upvotes: 1

Related Questions