问题
I have a QGraphicsScene "scene" and QGraphicsView "graphicsView".
I have a drawing method. When I need redraw all the graphics, I call this method. Everything is OK. But I realized that scene->clear() doesn't change the sceneRect.
Also I tried:
graphicsView->items().clear();
scene->clear();
graphicsView->viewport()->update();
After that, if I get the sceneRect by
QRectF bound = scene->sceneRect();
qDebug() << bound.width();
qDebug() << bound.height();
I expect the bound.width and bound.height to be '0'. But they aren't. I see the previous values everytime. How to clear sceneRect when I clear the scene itself?
It gives some problems that sceneRect remains the same, while using graphicsView->fitInView() method.I use following code:
QRectF bounds = scene->sceneRect();
bounds.setWidth(bounds.width()*1.007); // to give some margins
bounds.setHeight(bounds.height()); // same as above
graphicsView->fitInView(bounds);
Although I completely cleared the scene and added only one rather small rectangle, the rectangle didn't fit into view because of sceneRect remains too big.
I hope I could explain my problem.
回答1:
The better question is why do you need to set scene rectangle? In case you have a smaller scene don't set it. Instead add items to the scene and fit in view based on items bounding rectangle as in my example below:
#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);
}
In case you have a large scene with hundreds of items this approach will be slow because:
If the scene rect is unset, QGraphicsScene will use the bounding area of all items, as returned by itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a relatively time consuming function, as it operates by collecting positional information for every item on the scene. Because of this, you should always set the scene rect when operating on large scenes.
来源:https://stackoverflow.com/questions/34449357/qgraphicssceneclear-doesnt-change-scenerect