I know many of you are just looking for some reference code to copy so I put that here at the top, but if you want to learn more, a detailed explanation can be found in the video above and in the text below.

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

        self.label = QLabel("{}".format(self.slider.value()))
        main_layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.on_value_changed)

        self.slider.setMinimum(0)
        self.slider.setMaximum(50)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(5)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def on_value_changed(self, value):
        self.label.setText("{}".format(value))


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

Boilerplate Code

For us to work with QRadioButtons, we will need to setup a window to quickly do that. The code for which can be found below:

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout,
                              QWidget)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

Starting off at the top, we have some imports for the things we will need.

Lines 5-8, subclass QMainWindow in order to allow us to create our own custom main window to add content to. Then it initializes the class by running the super class’ init() method, and setting the title for the window to "My QRadioButton Window".

Line 9 created a QVBoxLayout. Lines 11-13 create a widget, adds the layout to that widget and sets it as the central widget for this application.

If you haven’t worked with layouts before, I have a tutorial covering them, but for now all you really need to know is that this line, and the lines below it make it so you can add widgets (like labels and push buttons) to your interface so that they are stacked vertically and stretch nicely when the window is resized.

Lines 16-20 define the main() function which creates an application initialized with the given command line arguments (sys.argv), creates a main window from our custom class, shows the window, and executes the application.

Lastly, lines 23 and 24 runs the main() function if this is the main file being run.

If you save the file and run it, it should look like this:

Now let’s slide into creating a QSlider!

Creating a QSlider

Starting off, we need to update line out imports to import QSlider as well as Qt so we can later set out slider as a horizontal slider:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider)
from PyQt5.QtCore import Qt

On line 13, we create our slider. QSliders by default are vertical, so we pass Qt.Horizontal so we can have a horizontal slider. Then we add the slider to the screen.

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

Setting the QSlider’s Value

It is common to have to set the value of a slider. QSliders only work with integers and by default go from zero to 99.

To set the slider’s value, all you need to do is use QSlider‘s setValue() method. In our example, after we add it to the layout, we set the value by passing it 25:

        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def on_value_changed(self, value):
        self.label.setText("{}".format(value))


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

Getting the QSlider’s Value

It is common to have to get the value of a slider. This is also easy. You just use QSlider‘s value() method.

In our example, on line 18, we are going to add a label, and set the text of that label as the slider’s value. Then we add the label to the layout.

        self.slider.setValue(25)

        self.label = QLabel("{}".format(self.slider.value()))
        main_layout.addWidget(self.label)

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

        self.label = QLabel("{}".format(self.slider.value()))
        main_layout.addWidget(self.label)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

Setting a Callback Function

A lot of times, you will want to react when the user changes the value of a slider. This can be done by setting up a callback function to the slider’s valueChanged signal.

In our example we will update the label when the user changes the value of the slider.

On line 21, we run the connect method on self.slider‘s valueChanged signal and pass it the function self.on_value_changed which we will define below. Note, self.on_value_changed does not have parentheses after it. We want to pass the function, not call it.

        main_layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.on_value_changed)

Then below the __init__ method, on line 27, we define on_value_changed(). It has a parameter value, that is the updated value. W

        self.setCentralWidget(widget)

    def on_value_changed(self, value):
        self.label.setText("{}".format(value))

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

        self.label = QLabel("{}".format(self.slider.value()))
        main_layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.on_value_changed)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def on_value_changed(self, value):
        self.label.setText("{}".format(value))


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

If we run that code, and move the slider all the way to the right, we should get:

You can move the slider as much as you please, and it will update the label with its value.

Min, Max, and Ticks

Lastly, we are going to go over some niceties. You may want to set the min or max values of the slider or have your slider have ticks (lines below it) to allow the user to more easily set a specific value. Let’s dig into how to do all that!

We are going to set the minimum to zero. To do that, on line 23 we use the slider’s setMinimum() method passing it 0. Similarly, we set the maximum to 50 by using the slider’s setMaximum() method passing it 50.

Below that we setup the ticks. On line 25, we set the tick position using setTickPosition() passing it QSlider.TicksBelow. Then, all you need to do is set the interval you want to see the ticks at. This is done by using the setTickInterval() method, passing it the interval. In our example we pass it 5.

        self.slider.valueChanged.connect(self.on_value_changed)

        self.slider.setMinimum(0)
        self.slider.setMaximum(50)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(5)

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QSlider, QLabel)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QSlider Window")
        main_layout = QVBoxLayout()

        self.slider = QSlider(Qt.Horizontal)
        main_layout.addWidget(self.slider)

        self.slider.setValue(25)

        self.label = QLabel("{}".format(self.slider.value()))
        main_layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.on_value_changed)

        self.slider.setMinimum(0)
        self.slider.setMaximum(50)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(5)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def on_value_changed(self, value):
        self.label.setText("{}".format(value))


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

If we run that code, we should get:

And those are the essentials of QSlider!

Similar Posts