如何在scrollArea中正确移动小部件

时间:2019-10-23 12:44:58

标签: python pyside2

我有一个带有QLabel作为内部小部件的简单QScrollArea。现在,我希望能够移动内部小部件,并且如果内部小部件离开可见区域,则滚动条应出现并正确移动(反之亦然)。我能够构建一个可移动的内部小部件,但需要一些滚动条帮助。到目前为止,这是我的代码:

from PySide2 import QtGui, QtCore, QtWidgets

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent=parent)

        self.setFixedSize(QtCore.QSize(600, 400))
        layout = QtWidgets.QHBoxLayout(self)
        self.scrollArea = QtWidgets.QScrollArea()
        self.innerWidget = QtWidgets.QLabel("Inner Widget")
        self.innerWidget.setFixedSize(QtCore.QSize(300,200))
        self.innerWidget.setStyleSheet("background-color: rgb(160, 160, 200)")
        self.scrollArea.setWidget(self.innerWidget)
        layout.addWidget(self.scrollArea)
        self.mouseOldPos = None

    def mousePressEvent(self, event):
        rect = self.innerWidget.rect()
        localPos = event.pos() - self.innerWidget.pos()
        if (localPos.x() > 0) and (localPos.y() > 0):
            if rect.contains(localPos.x(),localPos.y()):
                self.mouseOldPos = event.pos()

    def mouseMoveEvent(self, event):
        if self.mouseOldPos is not None:
            delta = self.mouseOldPos - event.pos()
            iwp = self.innerWidget.pos()
            self.innerWidget.move(iwp - delta)
            self.mouseOldPos = event.pos()
            self.scrollArea.ensureWidgetVisible(self.innerWidget)

    def mouseReleaseEvent(self, event):
        self.mouseOldPos = None

0 个答案:

没有答案