PDA

View Full Version : help with QGraphicsView



Erlendhg
22nd April 2007, 17:04
If I have a QGraphicsView and a QGraphicsScene set to it, and I want to add a rectangle:

How can I add it, so it's top left corner will always, no matter how big or small the scene or view is, be in the view's top left corner?

Thanks,
Erlend Graff

wysota
22nd April 2007, 17:11
I don't know if I understand the problem correctly but unless you scroll the view an element with position 0,0 will be at the left upper corner of the view.

Erlendhg
22nd April 2007, 17:23
Well, I will try to explain further:

When I add a rectangle:


eventScene.addRect(QRectF(0, 0, 40, 40));

That would make the rectangle appear centered in the view.

How can I add it so it would stretch from view coordinates 0,0 to 40,40?

marcel
22nd April 2007, 17:26
This is because your scene rect is smaller than your view rect. The scene is centered in the view.

Maybe you want to override QGraphicsView::drawForeground and make the rectangle always stay at view coordinates ( 0, 0 ).

Regards

Erlendhg
22nd April 2007, 21:14
How can I do that?

I tried this:


eventView = new QGraphicsView(ui.centralWidget);
eventView->setGeometry(QRect(5, 60, 591, 81));
eventView->setFrameShape(QFrame::Box);
eventView->setFrameShadow(QFrame::Plain);

eventScene = new scene;

eventView->setScene(eventScene);
eventScene->setSceneRect(0, 0, 480000, 50);

QPointF a = eventView->mapToScene(0, 0);

eventScene->addRect(QRectF(a.x(), a.y(), 100, 12), QPen(Qt::green), QBrush(Qt::blue));
eventScene->addRect(QRectF(a.x(), a.y()+12, 100, 12), QPen(Qt::red), QBrush(Qt::yellow));


but when I then scale the whole thing with let's say

eventView->scale(2, 2);
the blue box is cut away, because the top left corner is no longer (0,-14) but (0,0)!

And that is a problem for me. Any help further is really appreciated!

Erlend Graff

marcel
22nd April 2007, 21:23
Try this:


QGraphicsItem* rectItem = eventScene->addRect(QRectF(a.x(), a.y(), 100, 12), QPen(Qt::green), QBrush(Qt::blue));


Then, later, when you scale the view:


QRectF bbox = rectItem->boundingBox();
QPointF itemcenter = eventView->mapToScene( bbox->center() );
eventView->centerOn( itemcenter );


Remember that is the scene rect is larger than the bounding box of your items, and the items are anchored at (0,0), then they will never appear centered in the view. You will have to modify the scene rect for this, or translate your items.

Regards

marcel
22nd April 2007, 21:26
Also, instead of QGraphicsView::centerOn() you could try to use one of the QGraphicsView::ensureVisible() functions. They all should have the same result.

Regards