问题
This is a follow-up question. Here is the link to my previous question. The answer there works but the problem however I faced was that in the beginning, the line would be drawn to the mouse press taking it as the endpoint instead of been drawn from the mouse press taking it as the starting point. As suggested by a user there explicitly setting the sceneRect
solves the problem, but however after explicitly setting the sceneRect
the view stops adapting and showing scrollbar.
Here's a demo before adding sceneRect
As you could see the viewport automatically adjusts, when the mouse is over any of the edges, giving the user more space to draw. (Also note how the line is been drawn to the mouse press at the very beginning)
And Here is after if used self.setSceneRect(QtCore.QRectF(0, 0, 500, 500))
inside the constructor of the Scene
class
As you could see it doesn't adjust the viewport itself when the mouse is near the edges of the screen unlike how it happened previously.
Now coming to my question, is there a way to make the view adapts to the changes inside the scene automatically after setting the sceneRect
, or should I change sceneRect
manually like shown here?
回答1:
One possible solution is to update the sceneRect based on the size of the QGraphicsView, in addition to setting the view alignment to topleft:
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setMouseTracking(True)
scene = Scene()
self.setScene(scene)
def resizeEvent(self, event):
super().resizeEvent(event)
self.setSceneRect(
QtCore.QRectF(QtCore.QPointF(0, 0), QtCore.QSizeF(event.size()))
)
def main():
app = QtWidgets.QApplication(sys.argv)
view = GraphicsView()
view.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
If you want to observe the scrollbars then you can calculate the maximum between the previous sceneRect and the sceneRect based on the size of the viewport:
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setMouseTracking(True)
scene = Scene()
self.setScene(scene)
def resizeEvent(self, event):
super().resizeEvent(event)
r = QtCore.QRectF(QtCore.QPointF(0, 0), QtCore.QSizeF(event.size()))
self.setSceneRect(self.sceneRect().united(r))
来源:https://stackoverflow.com/questions/65795517/ensure-that-view-shows-scrollbar-and-adapts