PDA

View Full Version : How to resize a QGraphicsScene to a QGraphicsView?



CassioTC
21st March 2011, 21:11
Hi,

I'm having some trouble to resize the scene to the view size.

Here is the code:

bakgroundview.h

#ifndef BACKGROUNDVIEW_H
#define BACKGROUNDVIEW_H

#include <QObject>
#include <QGraphicsView>
#include <QGraphicsScene>

class BackgroundView : public QGraphicsView
{
Q_OBJECT
public:
BackgroundView(QGraphicsView *parent=0);
~BackgroundView() {};

signals:

public slots:

private:
QGraphicsView *view;
QGraphicsScene *scene;

protected:
void resizeEvent(QResizeEvent *event);
};

#endif // BACKGROUNDVIEW_H

bakgroundview.cpp


#include <QGraphicsLineItem>
#include <QResizeEvent>

#include "backgroundview.h"

BackgroundView::BackgroundView(QGraphicsView *parent)
: QGraphicsView(parent)
{
QGraphicsView *view = new QGraphicsView();
QGraphicsScene *scene = new QGraphicsScene();

scene->setSceneRect(0,0,view->width(),view->height());

QGraphicsLineItem* line = new QGraphicsLineItem ( 0,0, scene->width(), 0 );
QGraphicsLineItem* line2 = new QGraphicsLineItem ( scene->width(), 0 , scene->width(), scene->height() );
QGraphicsLineItem* line3 = new QGraphicsLineItem ( scene->width(), scene->height(), 0, scene->height() );
QGraphicsLineItem* line4 = new QGraphicsLineItem ( 0, 0, 0, scene->height() );

scene->addItem(line);
scene->addItem(line2);
scene->addItem(line3);
scene->addItem(line4);

setScene(scene);
}

void BackgroundView::resizeEvent(QResizeEvent *event)
{
//scene->setSceneRect(0, 0, event->size().width(), event->size().height());
QGraphicsView::resizeEvent(event);
}


main.cpp


#include <QApplication>
#include "backgroundview.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);


BackgroundView BgView;
BgView.showMaximized();

return app.exec();
}


When I remove the comment from the scene resize line, the window just close realy fast with an error. :mad:

How can I resize the scene to view every time the view was resized?

Thanks

qlands
22nd March 2011, 09:59
Hi,

You have an error in your code:

You have declared the private members in the .h:

QGraphicsView *view;
QGraphicsScene *scene;

But then in the constructor you re-declare them as local:
QGraphicsView *view = new QGraphicsView();
QGraphicsScene *scene = new QGraphicsScene();

Here you did not initialize the private member scene so because you use it in resizeEvent. it crash.

To fix it:

You need to change those lines to:
view = new QGraphicsView(); //Initialize the private member view
scene = new QGraphicsScene(); //Initialize the private member scene

Here because you already initialize scene resizeEvent will not crash.

Carlos

wysota
22nd March 2011, 10:03
Why do you want to change the scene size when the view resizes? Maybe you want to zoom the scene instead of changing its coordinate range? Because I don't see any reasonable explanation why someone would want to do that.