PyQt4的QSlider槽颜色定制

问题描述 投票:0回答:1

我目前正在做使用PyQt4的一个GUI。我的问题是:我该如何管理超过指数滑块值的特定范围内具有QSlider::groove:horizontal不同的背景颜色?下面是一个最小的工作示例:

from PyQt4 import QtCore, QtGui
#%%
data_range = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0]
color_range =['black','black','black','black','white','white',\
              'white','black','black','white','white','black']

class MyWidget(QtGui.QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(600,300,500,100)

        # Definition of the slider
        self.slider = QtGui.QSlider(minimum=0,\
        maximum= len(data_range)-1,\ 
        orientation=QtCore.Qt.Horizontal,\
        tickInterval=1)

        # Trying to customize it
        self.slider.setStyleSheet(\
        "QSlider::groove:horizontal {\
        border: 1px solid #999999;\
        height: 8px; \
        background: white;\
        margin: -4px 0;\
        }QSlider::handle:horizontal {\
        background-color: red;\
        border: 1px solid #5c5c5c;\
        border-radius: 0px;\
        border-color: black;\
        height: 8px;\
        width: 6px;\
        margin: -8px 2; \
        }")
       grid = QtGui.QGridLayout(self)
       hbox = QtGui.QHBoxLayout()
       hbox.addWidget(self.slider)
       grid.addLayout(hbox, 3, 0, 1, 3)


def main():
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

在这种情况下,Qslider的槽应该是从0黑:4,由4-白色:7,黑从7:9等。

我曾尝试使用self.slider.setStyleSheet() qt documentation以下,但徒劳...

任何帮助或替代的想法来装饰滑块将不胜感激。

python python-3.x qt pyqt pyqt4
1个回答
0
投票

我找到了答案,我的问题。通过使用以下功能:

def get_groove_color(color_range):

    groove_color_range = 'stop:0 ' + color_range[0]
    current_color = color_range[0]
    for i in range(0,len(color_range),1):
        if color_range[i] == current_color :
            continue
        else:
            current_color = color_range[i]
            groove_color_range += ', stop:'+ str((2*i-1)/2/len(color_range)) + ' ' + color_range[i-1] + ', stop:'+ str((2*i)/2/len(color_range)) + ' ' + color_range[i] 

    groove_color_range += ', stop:1 ' + color_range[-1]        
    return groove_color_range

我获得用于qlineargradient插值所需的颜色范围:

groove_color = get_groove_color(color_range)

最后只需要修改self.slider.setStyleSheet()的领域background-color凹槽颜色:

self.slider.setStyleSheet(\
    "QSlider::groove:horizontal {\
    border: 1px solid #999999;\
    height: 8px; \
    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, "+self.groove_color+");\
    margin: -4px 0;\
    }QSlider::handle:horizontal {\
    background-color: red;\
    border: 1px solid #5c5c5c;\
    border-radius: 0px;\
    border-color: black;\
    height: 8px;\
    width: 6px;\
    margin: -8px 2; \
    }")
© www.soinside.com 2019 - 2024. All rights reserved.