首页 > 解决方案 > 如何将 QScrollerProperties 应用于 QScroller,以摆脱超调?

问题描述

正如标题所说,我正在尝试制作一个使用 QScroller 和 Grabgesture 的 scrollArea,这样我就可以通过拖动小部件来滚动。我找到了一些很好的例子并让它发挥作用。现在我想消除当您拖得比小部件中的项目更远时发生的超调。
但是当我尝试调整 Qscroller 时,我似乎无法弄清楚如何将 QScrollerProperties 应用于 QScroller。这就是我假设您消除过冲的方式。
以下是代码示例:

import sys

from PyQt5.QtWidgets import (
    QApplication,
    QFormLayout,
    QGridLayout,
    QLabel,
    QScrollArea,
    QScroller,
    QScrollerProperties,
    QWidget,
)


class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        scroll_area = QScrollArea()
        layout = QGridLayout(self)
        layout.addWidget(scroll_area)

        scroll_widget = QWidget()
        scroll_layout = QFormLayout(scroll_widget)

        for i in range(200):
            scroll_layout.addRow(QLabel('Label #{}'.format(i)))

        scroll_area.setWidget(scroll_widget)

        scroll = QScroller.scroller(scroll_area.viewport())
        scroll.grabGesture(scroll_area.viewport(), QScroller.LeftMouseButtonGesture)
        scroll.scrollerPropertiesChanged.connect(self.PropsChanged) #Just to see if I could registre a change

        props = scroll.scrollerProperties()
        props.setScrollMetric(QScrollerProperties.VerticalOvershootPolicy,QScrollerProperties.OvershootAlwaysOff)
        props.setScrollMetric(QScrollerProperties.DragStartDistance, 0.01)

        #Apply Qscroller properties here somehow?
        print(scroll.scrollerProperties().scrollMetric(QScrollerProperties.DragStartDistance))
        scroll.scrollerProperties = props #Maybe? Doesn't seem to change the overshoot?


    def PropsChanged(self):
        print("Something is being changed??")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

我不知道如何从这里开始。任何帮助都会得到帮助:)

标签: python-3.xpyqt5gesture

解决方案


scroll.setScrollerProperties(props)设置新属性后只需调用。

当您调用时,scrollerProperties()您将获得当前属性的“副本”:它不是指向实际属性的指针,因此除非您将它们应用回滚动条,否则不会发生任何变化。

这几乎就像打电话self.font()

    font = self.font()
    font.setPointSize(20)
    # at this point, the widget font is still the same...
    # unless you do this:
    self.setFont(font)

这同样适用于几乎所有属性,例如text()/setText()用于标签,palette()/setPalette()等。

为了防止垂直过冲,您必须使用setScrollMetricwith VerticalOvershootPolicy,并将值设置为 OvershootAlwaysOff:

    props.setScrollMetric(QScrollerProperties.VerticalOvershootPolicy, 
        QScrollerProperties.OvershootAlwaysOff)
    scroll.setScrollerProperties(props)


推荐阅读