I created a custom qGraphicsRectItem which I added to my qGraphicsScene. I would like to add text to this custom rectangle using its local coordinates (i.e. adding to 0,0 places the item at the origin of my rectangle no matter where it its in my scene) When I try to do so, it uses my scene's coordinate system and the text appears out of the rectangle. Any ideas?
PackageRect::PackageRect(QString PackageName, qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent)
:QGraphicsRectItem(x, y, w, h, parent)
{
QGraphicsTextItem *text = new QGraphicsTextItem(PackageName, this);
text->setPos(0,0);
}
What you are trying to do, tends to be used in "Grouped" items.
There are several mapTo*
functions including:
http://doc.qt.io/qt-5/qgraphicsitem.html
QPointF mapToItem(const QGraphicsItem * item, const QPointF & point) const
QPointF mapFromItem(const QGraphicsItem * item, const QPointF & point) const
QPointF mapFromScene(const QPointF & point) const
QPointF mapToScene(const QPointF & point) const
Basically the context you are calling the mapping function from changes the behavior of the mapping call.
If you are inside a subclass of QGraphicsItem
, and you call this->mapToItem(myRect, QPointF(0,0));
it will return a value in terms of the coordinate system of the Rectangle.
And likewise, ff you are inside a subclass of QGraphicsItem
, and you call this->mapFromItem(myRect, QPointF(0,0));
it will return a value in terms of the coordinate system of the original item, where 0,0 is the upper left of the rectangle.
Here is more documentation on the coordinate system:
http://doc.qt.io/qt-5/graphicsview.html#the-graphics-view-coordinate-system
But if you are grouping objects in a QGraphicsView
, group them and move the group around.
http://doc.qt.io/qt-5/graphicsview.html#item-groups
http://doc.qt.io/qt-5/qgraphicsitemgroup.html#details
Hope that helps.