如何在 QGraphicsView 中设置精确的场景矩形

how to set exact scene rect in QGraphicsView

我对 QGraphicsView 有疑问,我不知道如何为 QGraphicsView 设置确切的视口。例如我写了下面的代码:

QGraphicsScene *scene = new QGraphicsScene();
QGraphicsEllipseItem * ellipse;
QPen pen(Qt::red);
QBrush brush(Qt::blue);
ellipse = scene->addEllipse(10,10,100,100,pen, brush);
ui->graphicsView->setScene(scene);
ui->graphicsView->setSceneRect(10,10,100,100);

我认为结果必须是视图重角内的圆圈,其直径等于视口的高度或宽度。 但是当我 运行 程序时,它在视图内显示了一个中等大小的圆圈,这意味着 graphicView 的 sceneRect 比我指定的要大。有人知道为什么吗?

我想你想要 fitInView():

// when graphicsView is visible:
ui->graphicsView->fitInView(ui->graphicsView->sceneRect(), Qt::KeepAspectRatio);

我自己找到了解决办法: 假设 exactRect 是您要放大的精确矩形:

QRectF exactRect(20, 10, 300, 200);
ui->graphicsView->setSceneRect(exactRect);
ui->graphicsView->setCenterOn(exactRect.center());
QMatrix mtx;
mtx.scale(ui->graphicsView->width()/exactRect.width(),
          ui->graphicsView->height()/exactRect.height());
ui->graphicsView->setMatrix(mtx);