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