PDA

View Full Version : Using QGraphicsItem::mapToScene



Casper14
17th July 2014, 16:23
Initially I thought this would be a trivial problem to solve, but I must be misundertanding something, because I just cannot get it working. I have subclassed QGraphicsItem to create my own custom QGraphicsItem, MyItem. This item is then added to the scene of a QGraphicsView.

In MyItem, I have implemented MyItem::itemChange, and I want to get the position of the item, but in the coordinates of the QGraphicsView's scene. However, when I use MyItem::mapToScene, I always receive the coordinates of the item, just multiplied by two. Here is the relevant code:



QVariant
MyItem::
itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == QGraphicsItem::ItemPositionChange)
{
double x = this->pos().x();
double y = this->pos().y();
QPointF scene = mapToScene(QPointF(x, y));
assert (this->scene() != 0);
std::cout << "item coordinates: " << x << " " << y << "\n";
std::cout << "scene coordinates: " << scene.x() << " " << scene.y() << "\n";
}

return QGraphicsItem::itemChange(change, value);
}

The incorrect output is then:


item coordinates: -27.2653 190.857
scene coordinates: -54.5306 381.714

I would expect mapToScene to return the same coordinates as where the item was drawn when I called this->scene()->addItem(myitem); in my QGraphicsView, which then calls MyItem::paint.

How can I know where in the scene the item is? Thanks!

stampede
18th July 2014, 21:57
I want to get the position of the item, but in the coordinates of the QGraphicsView's scene
Why do you need that ? Ideally an item should draw itself correctly without knowing where it is located.
If you really need it, you can use QGraphicsItem::scenePos() method, which is equivalent to QGraphicsItem::mapToScene(0,0).
btw. pos() will return position relative to item's parent, or scene:

(Qt docs) QGraphicsItem::pos
Returns the position of the item in parent coordinates. If the item has no parent, its position is given in scene coordinates.
So in your case you might be transforming the scene position via scene's transform again.

Casper14
22nd July 2014, 21:40
Thanks for your reply. I need it to ensure that the user does not move the QGraphicsItem outside the valid bounds of the scene. So I need to know where the item is relative to the scene's coordinates to calculate whether its position is valid.

In the end, I just added the item I want to draw at (0, 0), and then moved it myself using setPos(x, y). This way it lives in the same coordinate system as the scene and makes my life much easier. See http://osdir.com/ml/lib.qt.jambi/2008-05/msg00067.html