PyQt comes with a slider, QSlider. You can use this slider to select a value. A slider can be a great input widget for volume.

It allows a user to quickly change the value on a widget range, in contrast to a numeric counter. The range of a QSlider is from 0 to 100, where 100 is 100%.

Related Course: Create GUI Apps with Python PyQt5

QSlider

Create a slider

A slider can be horizontal or vertical. You can choose a type, when creating a slider. Either Qt.Horizontal or Qt.Vertical.

First import QSlider and Qt.

1
2
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QSlider

Then create a slider:

1
mySlider = QSlider(Qt.Horizontal, self)

Then set its geometry (position and size):

1
mySlider.setGeometry(30, 40, 200, 30)

And connect a method that’s called when changing its value:

1
mySlider.valueChanged[int].connect(self.changeValue)

slider pyqt

Example

The program below creates an empty window with a horizontal slider. If you want a vertical slider, don’t forget to change the geometry.

Copy and paste the code below to try a slider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSlider
from PyQt5.QtCore import Qt

class Example(QMainWindow):

def __init__(self):
super().__init__()

mySlider = QSlider(Qt.Horizontal, self)
mySlider.setGeometry(30, 40, 200, 30)
mySlider.valueChanged[int].connect(self.changeValue)

self.setGeometry(50,50,320,200)
self.setWindowTitle("Checkbox Example")
self.show()

def changeValue(self, value):
print(value)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

If you are new to Python PyQt, then I highly recommend this book.

Download Examples