PDA

View Full Version : Center QGraphicsTextItem at position



xdn
31st January 2013, 15:43
Hi all,

I would like to center a QGraphicsTextItem at a certain position in the scene. The Item is set to QGraphicsItem::ItemIgnoresTransformations and is thus not affected by zoom. If I try doing sth like "item.setPos(posx - item.boundingRect().width()/2)" it does not work, because boundingRect seems to refer to the rect at zoom 1.0 and at higher/lower zoomlevels this moves the item off center.
Furthermore at very high zoomlevels when maybe only two pixels of the scene are visible, I would like the item to be centered at the border between those two pixels and not starting at the border and extending only into the pixel to the right.

Is this positioning possible?

Santosh Reddy
31st January 2013, 15:58
I would like to center a QGraphicsTextItem at a certain position in the scene.
Do you mean, that you want a text fixed at the centre of the scene or at the centre of the view (motinor screen)?

xdn
31st January 2013, 19:40
I want the center of the text-item to be at some position in the scene.
item.setPos(100,100) would place the text's upper left corner at position 100,100 but I want the center of the text to be at that position.
And that is made more difficult by the zooming problems I describe above.

sedi
31st January 2013, 20:42
In my MainWindow I use this:


QRect rect=this->widget->view->viewport()->rect();
this->scene->setSceneRect(QRectF(0,0,rect.width(),rect.height() ));
Perhaps you should also look into the ->mapTo... and ->mapFrom... methods.

To know when the scene's size is being changed by the user I subclass the CentralWidget and plug myself into the resizeEvent, triggering a signal from there:


CentralWidget::CentralWidget(QWidget *parent) :
QWidget(parent)
{
}

void CentralWidget::resizeEvent(QResizeEvent *)
{
emit this->centralWidgetWasResized();
}
bool CentralWidget::event(QEvent * event)
{
if (event->type()==QEvent::Show) emit this->centralWidgetWasResized();
event->ignore();
return QWidget::event(event);
}

Actually I am not quite sure if this tackles your problem in the right way, but it might give you some ideas.

xdn
1st February 2013, 07:10
I'm sorry but I do not see how this would help me.

xdn
1st February 2013, 09:29
I found a not-so-clean way to do it. If in a view I correct the position of the items every time the zoom/scale changes, it works like this:

item->setPos(xpos - item->boundingRect().width()/2.0/transform().m11(), ypos);

But this will cause problems if two views show the same item but have different values for transform().m11() (i.e. zoom/scaling).
A better way would be to somehow have the items "position anchor" (I don't know how positioning is done internally) to be in its center as opposed to the upper left corner.

Any further help/comments are welcome.