PyQt5 comes with sliders out of the box.
A slider lets the user pick a number by dragging. In PyQt5 that is
QSlider. It comes in a horizontal and a vertical version, chosen with the
Qt.Horizontal and Qt.Vertical flags.
You connect it the same way you connect a button: with a signal.
A slider lets the user pick a number by dragging. In PyQt5 that is
QSlider. It comes with horizontal and vertical versions, chosen with the
Qt.Horizontal and Qt.Vertical flags.
Sliders can be either vertical or horizontal. We can connect them with a method the same way as we do with buttons.
A slider is often used in conjunction with a spinbox, QSpinBox. In this example we won’t use a spinbox, as that’s optional. You can connect a slider to any widget or functionality you want.
Slider example
We create a groupbox which contains 4 sliders. A slider is created with the class QSlider, which accepts the flags Qt.Horizontal or Qt.Vertical.
If you want to add a slider to your existing code, don’t forget to import QSlider from PyQt5.QtWidgets.
# pythonprogramminglanguage.com |
Working with the value
setMinimum(0)andsetMaximum(100)set the range.setValue(50)sets the starting position.value()returns the current number.valueChangedis a signal, connect it to a function withconnect().setTickInterval(10)puts small marks on the slider.setOrientation(Qt.Horizontal)sets the direction.
A label next to the slider that shows the value makes the connection obvious. Connect
the same signal to label.setNum and it updates as you drag.
Working with the value
setMinimum(0)andsetMaximum(100)set the range.setValue(50)sets the starting position.value()returns the current number.valueChangedis the signal.connect()it to a function.setTickInterval(10)puts small marks on the slider.setOrientation(Qt.Horizontal)sets the direction.setTracking(True)(the default) fires the signal while dragging, set it False for one signal when the user lets go.
Put a label next to the slider that shows the value. Connect the same signal to
label.setNum and it updates as the user drags, which makes it obvious the
slider works.
A slider next to a QSpinBox is a common pair, the spin box gives the
exact number and the slider shows it at a glance.
The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.
