Python PyQt4 slider with tick labels

前端 未结 2 2093
时光说笑
时光说笑 2021-01-03 01:34

I am new to PyQt4 and i am making a gui with QSlider.

By default the QSlider doesnt show you the values of your ticks. I searched and didnt find an easy way to do it

2条回答
  •  一整个雨季
    2021-01-03 02:03

    Sadly, there's no easy way to do this. You will have to make it manually. I just had to do it too, so you can have my implementation. Take into account that I only re-implemented what I needed, I hacked a bit the alignments and the valueChanged() API exhibits a very different behaviour.

    from PyQt4 import QtCore
    from PyQt4.QtGui import QSlider, QWidget, QVBoxLayout, QHBoxLayout, QLabel
    __author__ = 'Andres'
    
    
    class QCustomSlider(QWidget):
        def __init__(self, sliderOrientation=None):
            super(QCustomSlider, self).__init__()
            self._slider = QSlider(sliderOrientation)
    
            self.setLayout(QVBoxLayout())
    
            self._labelTicksWidget = QWidget(self)
            self._labelTicksWidget.setLayout(QHBoxLayout())
            self._labelTicksWidget.layout().setContentsMargins(0, 0, 0, 0)
    
            self.layout().addWidget(self._slider)
            self.layout().addWidget(self._labelTicksWidget)
    
        def setTickLabels(self, listWithLabels):
            lengthOfList = len(listWithLabels)
            for index, label in enumerate(listWithLabels):
                label = QLabel(str(label))
                label.setContentsMargins(0, 0, 0, 0)
                if index > lengthOfList/3:
                    label.setAlignment(QtCore.Qt.AlignCenter)
                if index > 2*lengthOfList/3:
                    label.setAlignment(QtCore.Qt.AlignRight)
                self._labelTicksWidget.layout().addWidget(label)
    
        def setRange(self, mini, maxi):
            self._slider.setRange(mini, maxi)
    
        def setPageStep(self, value):
            self._slider.setPageStep(value)
    
        def setTickInterval(self, value):
            self._slider.setTickInterval(value)
    
        def setTickPosition(self, position):
            self._slider.setTickPosition(position)
    
        def setValue(self, value):
            self._slider.setValue(value)
    
        def onValueChangedCall(self, function):
            self._slider.valueChanged.connect(function)
    

提交回复
热议问题