Solved QGraphicsItem incorrect center
-
Hi,
You don't seem to take into account the width of your text item when setting its position.
-
@Loc888 said in QGraphicsItem incorrect center:
line->boundingRect().center().x()
boundingRect().center()
is inline
item coordinates. You need to map it to scene coordinates, in order to get the real point, where you want to move your text in your scene... and no, these functions are not rubbish, if used correctly ;-)
-
@Pl45m4 Then how to set the data they return? They return qpolygonf, idk how to set the x and y from it.
-
Given a QPointF,
mapToScene
returns a QPointF. https://doc.qt.io/qt-5/qgraphicsitem.html#mapToScene -
You looked at the wrong function signature.
mapToScene
is overloaded multiple times.
TheQPolygonF
returning function (that takes aQRect
) is the wrong one in your case.
There is one to mapQPointF
s.There is also:
qreal QPointF::x() const
(same withy()
) to get (X,Y) separately. -
@Pl45m4 Doesn't work what so ever comeone..
QPointF pp = text->mapToScene(QPointF(line->pos().x(), line->pos().y())); text->setPos(pp);
Horrible.
-
I thought you want to display the text centered to your line item?
JustX
andY
alone will take the top left corner of your item, not the center.Come on, it's not that hard :)
You have to do the math on your own ( how and where to place your item and what points you need).
All functions work as intended and return what they should.This might help, if you haven't seen it before:
https://doc.qt.io/qt-5/graphicsview.html#the-graphics-view-coordinate-system
There is also this
(https://doc.qt.io/qt-5/qrectf.html#moveCenter)
to move the center of aQRectF
to a certain point. -
@Pl45m4 Can't use that moveTocenter, unapplicable.
-
Because it's
textItem->boundingRect().moveCenter(....)
I've made an example:
void MainWindow::centerItems() { auto textItem = ui->graphicsView->scene()->items().at(0); auto lineItem = ui->graphicsView->scene()->items().at(1); if(textItem == nullptr || lineItem == nullptr) return; QPointF center = lineItem->boundingRect().center(); QPointF newPoint(lineItem->mapToScene(center).x() - (textItem->boundingRect().width() / 2), lineItem->mapToScene(center).y() - (textItem->boundingRect().height() / 2)); textItem->setPos(newPoint); }
To use the
boundingRect
directly (moveCenter
) you have to callprepareGeometryChange
which I can't when being insideMainWindow
. It is possible that way, but you don't need to do that.
This would save you from calculating the new point, sincepos
is always in Item-Coordinates and it's the top-left point, not the center. -
@Pl45m4 I fixed it with the easier way, i just subtracted the centers in setPos, since it moves it to the topRight corner. The issue was caused by scaled()... I guess it mess up the center/origin, whatever it was. After i removed it, everything is correct.