2011-06-21 137 views

回答

3

您可以根據QScrollBar創建自己的ScrollBar類,並重新實現virtual void paintEvent (QPaintEvent *)方法。不要忘記調用原來paintEvent手柄,如果你看什麼你的亮點下的實際滾動條...

應該是這樣的:

void SrollBar::paintEvent(QPaintEvent * event) 
{ 
    QScrollBar::paintEvent(event); //Qt scroll bar is rendered now 
    QPainter p(this); 

    //here do what ever you want like painting rectangles with alpha = 0.5 ... 
} 
4

您可以通過繼承QScrollBar和更換做到這一點小部件的滾動條與您自己的,然後重寫paintEvent以調用超類paintEvent,然後在頂部繪製突出顯示。

paintEvent覆蓋中的重要內容是將繪圖限制和縮放到滾動條凹槽,同時避免在滑塊頂部繪圖。您可以通過剪切到凹槽矩形減去滑塊矩形(如initStyleOption(QStyleOptionSlider *)計算)來做到這一點。

此代碼是在Python,但它應該是相當簡單的翻譯到C++:

_ANNOTATION_SCROLLBAR_COLOUR = "gold" 
document_height = 100 
annotations = [(10, 20), (50, 51), (82, 85)] 

class AnnotatedScrollBar(QtGui.QScrollBar): 
    def paintEvent(self, event): 
     super(AnnotatedScrollBar, self).paintEvent(event) 
     p = QtGui.QPainter(self) 
     opt = QtGui.QStyleOptionSlider() 
     self.initStyleOption(opt) 
     gr = self.style().subControlRect(QtGui.QStyle.CC_ScrollBar, opt, 
             QtGui.QStyle.SC_ScrollBarGroove, self) 
     sr = self.style().subControlRect(QtGui.QStyle.CC_ScrollBar, opt, 
             QtGui.QStyle.SC_ScrollBarSlider, self) 
     p.setClipRegion(QtGui.QRegion(gr) - QtGui.QRegion(sr), 
         QtCore.Qt.IntersectClip) 
     x, y, w, h = gr.getRect() 
     c = QtGui.QColor(_ANNOTATION_SCROLLBAR_COLOUR) 
     p.setBrush(c) 
     c.setAlphaF(0.3) 
     p.setPen(QtGui.QPen(c, 2.0)) 
     yscale = 1.0/document_height 
     p.drawRects([QtCore.QRect(x, y + h * start * yscale - 0.5, 
            w, h * (end - start) * yscale + 1) 
        for start, end in annotations])