0
我很难找到QScrollBar的滑块的正确中心(我需要粘贴一个文本小部件来显示滑块的位置)。我试着通过将滑动条的位置除以文档宽度来标准化滑块的位置,然后通过它的width()来缩放它。但这并不准确,因为滚动条的装饰和按钮没有被考虑在内。所以当你拖动标签时,标签就会徘徊,不会坚持到中心。 下面是我目前的代码,它需要考虑QScrollBar的按钮,框架等来找到滚动区域的正确开始和结束位置。 有人可以帮忙吗?跟踪QScrollBar的中心
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class PageScroller(QScrollBar):
'''Set the total number of pages.'''
def __init__(self, parent=None):
super(PageScroller, self).__init__(parent)
self.pageIndicator = QLabel('|', parent)
self.valueChanged.connect(self.updateSlider)
self.setOrientation(Qt.Orientation.Horizontal)
self.setPageStep(1)
def updateSlider(self, event):
scrollAreaWidth = self.maximum() - self.minimum() + self.pageStep()
sliderPos = (self.sliderPosition() + self.pageStep()/2.0)/float(scrollAreaWidth) * self.width()
indicatorPos = QPoint(sliderPos - self.pageIndicator.width()/2, -self.pageIndicator.height())
self.pageIndicator.move(self.mapToParent(indicatorPos))
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
#app.setStyle('plastique') # tyhis makes the sliding more obvious
mainWindow = QWidget()
layout = QVBoxLayout(mainWindow)
s = PageScroller(mainWindow)
layout.addWidget(s)
mainWindow.resize(400, 100)
mainWindow.show()
sys.exit(app.exec_())
谢谢。我必须添加'None'作为style.subControlRect()的第四个参数,因为一些样式似乎期望一个widget作为第四个控件(不太确定原因)。尽管偏移量有点不同(有时它位于中心,有时略偏离边),但现在这种方式跟不同样式的轨迹要好得多。但我可以忍受这一点。谢谢! – 2012-07-18 23:10:42