qt - 突出显示滚动条

标签 qt qt4

我想突出显示滚动条的某些部分,例如在谷歌浏览器中突出显示搜索。

参见 http://dl.dropbox.com/u/17404614/scrollbar.JPG

是否可以使用 Qt 来实现这一点?

谢谢

最佳答案

您可以通过子类化 QScrollBar 并用您自己的滚动条替换小部件的滚动条,然后覆盖 paintEvent 以调用父类(super class) paintEvent 和然后在上面画高光。

paintEvent 重写中的重要事项是将绘图限制和缩放到滚动条凹槽,同时避免在 slider 顶部绘图。您可以通过剪裁到凹槽矩形减去 initStyleOption(QStyleOptionSlider *) 计算的 slider 矩形来执行此操作。

此代码是用 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])

关于qt - 突出显示滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6432656/

相关文章:

c++ - QStyle所有权

c++ - 文本对齐 : Right in <span> or <div> (with HTML and C++)

c++ - 这个 Qt 样板构造函数为什么不是递归的?

c++ - Qt 在不触发 moveEvent 方法的情况下移动 QWidget?

c++ - 在 QModelIndex 中存储两种不同的类型

c++ - QTableView 中选中的行,复制到 QClipboard

c++ - 专业环境中的 Qt

c++ - 自定义小部件上 float 类型的 Q_PROPERTY 未出现在属性编辑器中

c++ - QPushButton 中的两种颜色文本

qt - 对全局属性 QML 的写入无效