0

I'm having an issue with PyQt5 QSlider.

I have multiple QSliders in a Widget. Now I want to update a corresponding QLabel when the handle of the slider is released. Therefore I connected all sliders inside a for loop, where I pass the slider and the Label as argument.

mot1_slider = QSlider(Qt.Horizontal)
    mot1_value = QLabel('0')
    mot2_slider = QSlider(Qt.Horizontal)
    mot2_value = QLabel('0')
    mot3_slider = QSlider(Qt.Horizontal)
    mot3_value = QLabel('0')
    trav_slider = QSlider(Qt.Horizontal)
    trav_value = QLabel('0')
    temp_slider = QSlider(Qt.Horizontal)
    temp_value = QLabel('0')
    air_slider = QSlider(Qt.Horizontal)
    air_value = QLabel('0')

    sliders = [mot1_slider, mot2_slider, mot3_slider, trav_slider, temp_slider, air_slider]
    slider_values = [mot1_value, mot2_value, mot3_value, trav_value, temp_value, air_value]

    //[removed for readability, here i add the elements into a QGroupBox]

    for slider, value_label in zip(sliders, slider_values):
        slider.sliderReleased.connect(lambda: self.slider_released(slider,value_label))

def slider_released(self, slider, value_label):
    value_label.setText(slider.value())

If I run this, the label value keeps showing 0. If I do print(slider.value()) I also get 0.

What am I missing?

Hope anyone of you can help me with this problem. Thanks!

  • Thank you. Will test that on Friday when I am back at the office. Could you also explain to me, what the `slider=slider` part does? I'm quite new to python. – MrMarlin May 02 '18 at 20:10
  • It caches the value of the current loop variable as a default argument. If you don't do that, the `lambda` will only see the last value. In fact, there are *two* loop variables, so the code needs to be `slider.sliderReleased.connect(lambda slider=slider, value_label=value_label: self.slider_released(slider, value_label))`. – ekhumoro May 02 '18 at 21:40

0 Answers0