2016-07-29 42 views
0

我試圖更改QSlider上的手柄顏色失敗。我如何將其更改爲自定義顏色?我已經使用了QSlider子類,以便我可以重新實現繪畫事件並在其上繪製我自己的矩形 - 現在我想設置句柄的顏色。在子類的小工具的創造者,我這樣做:如何更改QSlider上的手柄顏色

setStyleSheet("handle:horizontal {color: red}"); 

我已經嘗試了各種顏色之外的其他屬性,包括背景顏色等的 - 沒有作出任何改變都在窗口小部件 - 它仍然保持默認灰色。我發誓我的代碼根本沒有執行,但我在調試器中檢查過它,它是。

我試着將setStyleSheet移動到我的paintEvent中;這沒有什麼區別。這裏是的paintEvent - 我不知道它的問題,但我懷疑我會被問,如果我不包括它

void FilledSlider::paintEvent(QPaintEvent *ev) { 
    QStyleOptionSlider opt; 
    initStyleOption(&opt); 

    opt.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle; 


if (tickPosition() != NoTicks) 
    { 
     opt.subControls |= QStyle::SC_SliderTickmarks; 
    } 

    QRect groove_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); 
    QSlider::paintEvent(ev); 
    int grooveCenter = groove_rect.bottom() - (groove_rect.bottom() - groove_rect.top())/2.0; 
    QRect fillRectangle; 
    int left; 
    int width; 
    if(direction < 0) 
    { 
     left = groove_rect.left() + ((1.0 -filledPercentage) * groove_rect.width()); 
     width = filledPercentage * groove_rect.width(); 
    } 
    else 
    { 
     left = groove_rect.left(); 
     width = groove_rect.width() * filledPercentage; 
    } 
    fillRectangle.setRect(left, grooveCenter, width, 0.2*groove_rect.height()); 
    QPainter painter(this); 
    painter.fillRect(fillRectangle, QBrush(Qt::red)); 
} 
+0

你從哪裏學習如何編寫這個繪畫事件?好奇你使用的參考文獻。這可能會幫助我找到答案。 –

+1

對應於[this](http://doc.qt.io/qt-4.8/stylesheet-examples.html#customizing-qslider)嘗試'setStyleSheet(「QSlider :: handle:horizo​​ntal {background-color:red;} 「);'。如果它不起作用,可以使用偶然的'QSlider'而不是子類來嘗試。你可能會損壞'paintEvent'或其他東西。 – ilotXXI

+0

我從這裏複製了繪畫事件:http://stackoverflow.com/questions/17101378/coloring-qslider-for-particular-range – jhowland

回答

0

與此相應的嘗試setStyleSheet(「QSlider: :handle:horizo​​ntal {background-color:red;}「);.

這就是答案,謝謝iloXXI!