QGraphicsScene::clear 不会改变 sceneRect

meh*_*tfa 5 c++ qt qgraphicsview qgraphicsscene

我有一个 QGraphicsScene“场景”和 QGraphicsView“graphicsView”。

我有一个画图的方法。当我需要重绘所有图形时,我调用这个方法。一切都好。但我意识到 scene->clear() 不会改变 sceneRect。

我也尝试过:

graphicsView->items().clear();
scene->clear();
graphicsView->viewport()->update();
Run Code Online (Sandbox Code Playgroud)

之后,如果我通过以下方式获取 sceneRect

QRectF bound = scene->sceneRect();
qDebug() << bound.width();
qDebug() << bound.height();
Run Code Online (Sandbox Code Playgroud)

我希望bound.width和bound.height为“0”。但他们不是。我每次都会看到以前的值。当我清除场景本身时如何清除 sceneRect?

使用 GraphicsView->fitInView() 方法时,场景矩形保持不变会带来一些问题。我使用以下代码:

QRectF bounds = scene->sceneRect();
bounds.setWidth(bounds.width()*1.007);          // to give some margins
bounds.setHeight(bounds.height());              // same as above
graphicsView->fitInView(bounds);
Run Code Online (Sandbox Code Playgroud)

虽然我完全清除了场景并只添加了一个相当小的矩形,但由于 sceneRect 仍然太大,所以该矩形不适合视图。

我希望我能解释我的问题。

Ale*_*kov 1

更好的问题是为什么需要设置场景矩形?如果您的场景较小,请不要设置它。相反,将项目添加到场景中并根据项目边界矩形适合视图,如下面的示例所示:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsRectItem>
#include <QPointF>
#include <QDebug>
#include <qglobal.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    _scene = new QGraphicsScene(this);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setScene(_scene);

    connect(ui->button, SIGNAL(released()), this, SLOT(_handleRelease()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

int MainWindow::_random(int min, int max)
{
    return qrand() % ((max + 1) - min) + min;
}

void MainWindow::_handleRelease()
{

    _scene->clear();

    QGraphicsRectItem* pRect1 = _scene->addRect(0, 0, _random(50,100), _random(50,100));
    QGraphicsRectItem* pRect2 = _scene->addRect(0, 0, _random(20,50), _random(20,50));

    pRect1->setPos(QPoint(40,40));
    pRect2->setPos(QPoint(20,20));

    ui->graphicsView->fitInView(_scene->itemsBoundingRect(),Qt::KeepAspectRatio);
}
Run Code Online (Sandbox Code Playgroud)

如果您有一个包含数百个项目的大场景,那么这种方法会很慢,因为:

如果场景矩形未设置,QGraphicsScene 将使用 itemsBoundingRect() 返回的所有项目的边界区域作为场景矩形。然而,itemsBoundingRect() 是一个相对耗时的函数,因为它通过收集场景中每个项目的位置信息来进行操作。因此,在大场景上操作时应始终设置场景矩形。