PyQt5 QSlider | Python

Slider in PyQt5 is used to set a value with the help of an indicator which can move back and forth over a graphical slide or bar. Many times one needs to provide values which lie between a range and in such cases slider is very useful. QSlider is the class used to add slider in an application.

Example:

A window has a slider and a label(QSlider). The size of the text gets scaled in or out as one move the indicator of the slider.

filter_none

edit
close

play_arrow

link
brightness_4
code

from PyQt5 import QtCore, QtGui, QtWidgets
import sys
  
class Ui_MainWindow(object):
  
    def setupUi(self, MainWindow):
  
        MainWindow.resize(550, 393)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
  
        self.slider = QtWidgets.QSlider(self.centralwidget)
        self.slider.setGeometry(QtCore.QRect(190, 100, 160, 16))
        self.slider.setOrientation(QtCore.Qt.Horizontal)
  
        # After each value change, slot "scaletext" will get invoked.
        self.slider.valueChanged.connect(self.scaletext)
  
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(230, 150, 301, 161))
          
        # set initial font size of label.
        self.font = QtGui.QFont()
        self.font.setPointSize(7)
        self.label.setFont(self.font)
        MainWindow.setCentralWidget(self.centralwidget)
  
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
  
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "QSlider"))
          
    def scaletext(self, value):
        # Change font size of label. Size value could 
        # be anything consistent with the dimension of label.
        self.font.setPointSize(7 + value//2)
        self.label.setFont(self.font)
      
      
if __name__ == "__main__"
    app = QtWidgets.QApplication(sys.argv) 
    
    MainWindow = QtWidgets.QMainWindow() 
    ui = Ui_MainWindow() 
    ui.setupUi(MainWindow) 
    MainWindow.show() 
    sys.exit(app.exec_()) 

chevron_right


Output:




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.