2015-12-24 40 views
1

我有一個QGraphicsScene「場景」和QGraphicsView「graphicsView」。QGraphicsScene :: clear不會改變sceneRect

我有一個繪圖方法。當我需要重繪所有圖形時,我稱這種方法。一切都好。但是我意識到scene-> clear()不會改變sceneRect。

我也試過:

graphicsView->items().clear(); 
scene->clear(); 
graphicsView->viewport()->update(); 

之後,如果我通過

QRectF bound = scene->sceneRect(); 
qDebug() << bound.width(); 
qDebug() << bound.height(); 

得到sceneRect我期待bound.width和bound.height是 '0'。但他們不是。我每次都能看到以前的值。當我清除場景本身時如何清除sceneRect?

它給出了sceneRect仍然是相同的一些問題,同時採用graphicsView-> fitInView()method.I使用下面的代碼:

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

雖然我完全清除現場,只加一個相當小的矩形,由於sceneRect仍然太大,矩形不適合放入視圖。

我希望我能解釋我的問題。

回答

0

更好的問題是爲什麼你需要設置場景矩形?如果你有一個較小的場景,不要設置它。相反,基於項目邊框如下面的示例所示添加項目到現場,並適合視圖:

#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); 
} 

如果你有一個大的場景與數百個項目的這一做法將是緩慢的,因爲:

如果未設置場景矩形,QGraphicsScene將使用由itemsBoundingRect()返回的所有項目的邊界區域 作爲場景矩形。 但是,itemsBoundingRect()是一個相對耗時的功能,因爲它通過收集場景上每個項目的位置信息來操作。因此,當在大場景中操作 時,應始終設置場景矩形。

+0

使用graphicsView-> fitInView(scene-> itemsBoundingRect())代替graphicsView-> fitInView(scene-> sceneRect())解決了我的問題。但sceneRect仍然太大。刪除項目不會更改sceneRect。我認爲這個問題將在未來對我產生一些問題:) – mehmetfa

+0

@mehmetfa \t 創建場景後不需要設置場景矩形。如果沒有設置,那麼它將總是基於內部項目的邊界矩形進行計算。你是否嘗試刪除你設置場景矩形的那一行? –

+0

@mehmetfa如果您的問題已解決,請將問題標記爲已解決。 –