Search code examples
pythonpyside6

pyside6 Is it possible to connect QSlider.valueChanged with QLabel.setText in one line?


I have a GUI and I want to connect a slider and a label showing the current slider value. The QSlider.valueChanged event returns an integer, while QLabel.setText needs a string. Is there a possibility, to connect these both elements in one line instead of writing an extra function?

The long (and only?) way:

class MainWindow(QMainWindow):
    def __init__():
        ...
        self._label = QLabel('hello')
        self._slider = QSlider()
        self._slider.valueChanged.connect(self.set_value)
        ...

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

Is there a possibility to write it in one line? The following throws an error because it passes an int instead of a string.

class MainWindow(QMainWindow):
    def __init__():
        ...
        self._label = QLabel('hello')
        self._slider = QSlider()
        self._slider.valueChanged.connect(self._label.setText)
        ...

Solution

  • Use QLabel.setNum().

    self._slider.valueChanged.connect(self._label.setNum)