如何实现自己的QScrollArea

时间:2020-04-23 07:00:25

标签: python pyqt pyqt5 qscrollarea

我正在尝试了解QScrollArea用于实现自己的MyQScrollArea小部件的方式。 MyQScrollArea应该使用setViewportMargins。为此,我写了一个最小的工作示例,如下所示:

from PyQt5 import QtWidgets
import sys

class MyScrollArea(QtWidgets.QAbstractScrollArea):
    def __init__(self):
        super().__init__()

        self.label = QtWidgets.QLabel(", ".join(map(str, range(100))), self)

        hScrollBar = self.horizontalScrollBar()

        hScrollBar.setRange(0, self.label.sizeHint().width() - self.sizeHint().width())
        hScrollBar.valueChanged.connect(self._HScrollBarValueChanged)

        self.setViewportMargins(100, 0, 0, 0)
        self._HScrollBarValueChanged(0)

    def _HScrollBarValueChanged(self, value):
        self.label.move(-value + self.viewportMargins().left(), 0)

def main():
    app = QtWidgets.QApplication(sys.argv)
    scroll = MyScrollArea()
    scroll.show()
    app.exec_()

if __name__ == "__main__":
    main()

代码结果如下所示:

Widget before scrolling

但是,在滚动后,内部小部件会移出视口并在某个区域进行绘制,我不希望对其进行绘制:

Widget after scrolling

我在做错什么,如何使setViewportMargins功能正常工作?

1 个答案:

答案 0 :(得分:2)

除了每次修改小部件的几何形状时都要修改QScrollBar的属性之外,还必须将QLabel设置为视口的子项:

import sys

from PyQt5 import QtWidgets


class MyScrollArea(QtWidgets.QAbstractScrollArea):
    def __init__(self):
        super().__init__()

        self.label = QtWidgets.QLabel(", ".join(map(str, range(100))), self.viewport())

        self.setViewportMargins(100, 0, 0, 0)
        self.horizontalScrollBar().valueChanged.connect(
            self.on_hscrollbar_value_changed
        )
        self.update_scrollbar()

    def on_hscrollbar_value_changed(self, value):
        self.label.move(-value, 0)

    def update_scrollbar(self):
        self.horizontalScrollBar().setRange(
            0, self.label.sizeHint().width() - self.viewport().width()
        )
        self.horizontalScrollBar().setPageStep(self.viewport().width())

    def resizeEvent(self, event):
        self.update_scrollbar()
        super().resizeEvent(event)


def main():
    app = QtWidgets.QApplication(sys.argv)
    scroll = MyScrollArea()
    scroll.show()
    app.exec_()


if __name__ == "__main__":
    main()