开发者

Highlight a Scroll Bar

开发者_运维问答I want to highlight some portions of the scroll bar like highlight search in google chrome.

See http://dl.dropbox.com/u/17404614/scrollbar.JPG

Is it possible to use Qt to achieve this?

Thanks


You can do this by subclassing QScrollBar and replacing the widget's scrollbar with your own, and then overriding paintEvent to call the superclass paintEvent and then draw highlights on top.

The important thing in the paintEvent override is to confine and scale your drawing to the scrollbar groove while avoiding drawing on top of the slider. You can do this by clipping to the groove rectangle minus the slider rectangle as calculated by initStyleOption(QStyleOptionSlider *).

This code is in Python but it should be fairly straightforward to translate to 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])


You can create your own ScrollBar class based on the QScrollBar and re-implement the virtual void paintEvent ( QPaintEvent * ) method. Don't forget to call the original paintEvent handle if you what to see the actual scroll bar under your highlight ...

Should look like this:

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 ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜