【发布时间】:2021-09-11 21:10:22
【问题描述】:
我试图了解QGraphicsView.fitInView 的行为,但这对我来说似乎很奇怪。我有以下最小示例代码
import sys
from PyQt5.QtGui import QPen
from PyQt5.QtCore import Qt, QLineF
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QWidget, QApplication
class MyGraphicsScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setSceneRect(0, 0, 250, 500)
pen = QPen(Qt.black, 1, Qt.DashLine)
pen.setCosmetic(True)
self.addLine(QLineF(self.sceneRect().topLeft(), self.sceneRect().topRight()), pen)
self.addLine(QLineF(self.sceneRect().bottomLeft(), self.sceneRect().bottomRight()), pen)
self.addLine(QLineF(self.sceneRect().topLeft(), self.sceneRect().bottomLeft()), pen)
self.addLine(QLineF(self.sceneRect().topRight(), self.sceneRect().bottomRight()), pen)
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.view = QGraphicsView(self)
self.view.setGeometry(0, 0, 300, 300)
self.scene = MyGraphicsScene()
self.view.setScene(self.scene)
self.view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
app = QApplication(sys.argv)
window = MyWidget()
window.show()
sys.exit(app.exec_())
现在,我想要实现的是我可以将场景矩形设置为我想要的任何东西,然后调用QGraphicsView.fitInView 以适当放大或缩放场景以使其覆盖整个图形视图。在这个简单的示例中,我希望代码可以放大我在整个图形视图中绘制的矩形(它只是场景边界框)。所以顶部和底部边缘应该接触图形视图的边界。但是,这就是我得到的
特别奇怪的是,如果我不调用fitInView,那么我绘制的框会比图形视图大,并且会强制垂直滚动条。
我的问题有两个:
- 为什么会这样?显然,我不理解
fitInView的行为,并且 - 如何实现我想要的行为,即正确缩放图形场景/视图,使矩形到达图形视图的边缘?
【问题讨论】:
标签: python pyqt pyqt5 qgraphicsview qgraphicsscene