PDA

View Full Version : Centering a Widget in Graphics View



tbcpp
22nd June 2009, 15:45
I've been trying for some time now to squash a bug that I can't seem to figure out. I'm using a QGraphicsView as a parent window for my child dialogs. This way I can have a animated background behind my half transparent dialogs.

The issue is that these dialogs keep appearing in random locations in the QGraphicsView. They start more or less in the center of the view, but as I create and destroy them, they seem to be created in random locations in the view. Here's the code I use to create the dialogs, this is in my subclassed QGraphicsScene:



ab = getCurrentPanel(poffset); // Get the next dialog QWidget based on the current id
ab->load(); // perform some initial data population
cproxy = addWidget(ab, Qt::Widget );
QTransform transform;
transform.translate(0, 0);
cproxy->setTransform(transform);
parentView->centerOn(cproxy);


All the getCurrentPanel() does is return a QWidget pointer to my dialog based on the dialog Id being sent. The constructor for this dialog just passes NULL to the QWidget constructor, so that's not the issue.

Any ideas?

Thanks

shentian
22nd June 2009, 19:38
QGraphicsView::centerOn just adjusts the scroll bars of the view. The API doc says:


Note: If the item is close to or outside the border, it will be visible in the view, but not centered.

If you don't translate / scroll your view, the origin of the scene will be in the centre of your view. So maybe this will work for you:



QTransform transform;
transform.translate(-cproxy->width() / 2.0, -cproxy->height() / 2.0);
cproxy->setTransform(transform);

tbcpp
22nd June 2009, 19:56
Unfortunately, no that doesn't work. Firstly, it seems that QGraphicsProxies don't have a "width" or "height" property, I changed it to:



transform.translate(-cproxy->size().width() / 2.0, -cproxy->size().height() / 2.0);


and it compiles and runs, but I get the same issues.

Any other ideas?

luf
22nd June 2009, 20:55
Had som similar issues, and I ended up drawing a transparent QRect that was the way above the size of the GraphicsView, and made sure the widgets were placed within this one. That way centerOn worked like a charm.

I do think this is by design, and not a bug...

aamer4yu
23rd June 2009, 06:18
You could try QGraphicsView::fitInView also. Not sure if it will help, but I guess so