Reputation: 169
I'm working on a Qt project, the user draws points with mouse clicks. I'm trying to print the positions of the points using the following code. The program always prints the position as QPointF(0, 0).
QList<QGraphicsItem *> list = scene->items();
foreach( QGraphicsItem * item, list )
{
qDebug()<<item->pos();
}
Upvotes: 1
Views: 2334
Reputation: 27611
The documentation for QGraphicsScene::addEllipse states: -
Creates and adds an ellipse item to the scene, and returns the item pointer. The geometry of the ellipse is defined by rect, and its pen and brush are initialized to pen and brush. Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0).
The function is defined as: -
QGraphicsEllipseItem * QGraphicsScene::addEllipse ( const QRectF & rect, const QPen & pen = QPen(), const QBrush & brush = QBrush() )
The rect passed to the function provides the local coordinates of the item and the item is positioned at (0,0).
You need to set the position of the item using the pointer returned from addEllipse and calling setPos()
QGraphicsEllipseItem* pEllipse = scene->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,QPen(), QBrush(Qt::SolidPattern));
pEllipse->setPos(xPos, yPos); // where xPos and yPos are the scene coordinates
When retrieving the item's position, although the function QGraphicsItem::pos will return the item's parents coordinates which may be scene coordinates if no parent exists, you'd be better off calling QGraphicsScene::scenePos to guarantee that the coordinates returned are actually scene coordinates, even if you add parent items at a later stage.
QList<QGraphicsItem *> list = scene->items();
foreach( QGraphicsItem * item, list )
{
qDebug() << item->scenePos();
}
Upvotes: 3
Reputation: 18504
You should also setPos()
to item and in this case these methods will give you correct output. I suppose that now your code is something like:
scene->addEllipse(x, y, w,h);
If you add ellipse, rect or something else you should to know that:
Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0).
There is information about this in documentation. So you should setPos()
by yourself after usage of addSomeItem()
You can check also this good answer.
As doc said:
returns the position of the item in parent coordinates. If the item has no parent, its position is given in scene coordinates. The position of the item describes its origin (local coordinate (0, 0)) in parent coordinates; this function returns the same as mapToParent(0, 0). For convenience, you can also call scenePos() to determine the item's position in scene coordinates, regardless of its parent.
http://qt-project.org/doc/qt-4.8/qgraphicsitem.html#pos
Upvotes: 2