QtGui.QSlider
A QtGui.QSlider
is a widget that has a simple handle. This handle can be pulled back and forth. This way we are choosing a value for a specific task. Sometimes using a slider is more natural than entering a number or using a spin box.
In our example we will show one slider and one label. This time the label will display an image. The slider will control the label.
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode PyQt4 tutorial This example shows a QtGui.QSlider widget. author: Jan Bodnar website: zetcode.com last edited: September 2011 """ import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) sld.setFocusPolicy(QtCore.Qt.NoFocus) sld.setGeometry(30, 40, 100, 30) sld.valueChanged[int].connect(self.changeValue) self.label = QtGui.QLabel(self) self.label.setPixmap(QtGui.QPixmap('mute.png')) self.label.setGeometry(160, 40, 80, 30) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QtGui.QSlider') self.show() def changeValue(self, value): if value == 0: self.label.setPixmap(QtGui.QPixmap('mute.png')) elif value > 0 and value <= 30: self.label.setPixmap(QtGui.QPixmap('min.png')) elif value > 30 and value < 80: self.label.setPixmap(QtGui.QPixmap('med.png')) else: self.label.setPixmap(QtGui.QPixmap('max.png')) def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
In our example we simulate a volume control. By dragging the handle of a slider, we change an image on the label.
sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
Here we create a horizontal QtGui.QSlider
.
self.label = QtGui.QLabel(self) self.label.setPixmap(QtGui.QPixmap('mute.png'))
We create a QtGui.QLabel
widget and set an initial mute image to it.
sld.valueChanged[int].connect(self.changeValue)
We connect the valueChanged
signal to the user defined changeValue() method.
if value == 0: self.label.setPixmap(QtGui.QPixmap('mute.png')) ...
Based on the value of the slider, we set an image to the label. In the above code, we set a mute.png
image to the label if the slider is equal to zero.
Figure: QtGui.QSlider widget