[Solved] QGraphicsIte setPos , moveBy - how do they work?
-
I looked at the "colliding mouse example":http://doc.qt.nokia.com/4.7-snapshot/graphicsview-collidingmice.html that ships with Qt.
It took me several days to figure out
@setPos(mapToParent(0,1));@moves a QGraphicsItem downwards, everytime 'advance' (QGraphicsView function) is called. I don't understand how this works.
(This is not part of the code, but I modified the 'setPos' function slightly to see how it works)
I had to rummage though the code to figure out what was moving the QGraphicsItem. I expected to see something like
@setPos(mapToParent(0,ypos));@
to move something downwards, with ypos incremented in 'advance' member function in QGraphicsItem. This seems more intuitive to me. However, it seems this causes the item to move with a constant acceleration.
I also saw another function somewhere else that works exactly the same way (Correct me if I am wrong)
@moveBy(0,1);@Now this seems intuitive to me. Everytime advance is called, the item is 'moved by' (0,1)
Could somebody explain how setPos works?
Thanks! -
The confusion does not come from your interpretation of "setPos" (which acts as you expect), but from the "mapToParent" function
THIS is the important point:
The "mapToParent" function converts a coordinate in item coordinates to coordinate in parent's coordinate system (or scene coordinates if no parent)For example, if you have a mouse "myMouse" at (10,10) in your scene:
- The "myMouse" local coordinates are (0,0), i.e origin of the mouse item
- The "myMouse" coordinate in scene coordinates are (10,10).
A call myMouse.mapToParent(0,0) will return (10,10);
A call myMouse.mapToParent(0,1) will return (10,11);and this is the point:
@myMouse.setPos(10,10); /* Position the mouse in it's parent coordinate system : (10, 10) /
newPos = myMouse.mapToParent(0,1); / newPos = (10,10) + (0,1) = (10, 11); /
myMouse.setPos(newPos); / Position the mouse in it's parent coordinate system : (10, 11) /
newPos = myMouse.mapToParent(0,1); / newPos = (10,11) + (0,1) = (10, 12); /
myMouse.setPos(newPos); / Position the mouse in it's parent coordinate system : (10, 12) */@and so on...
Note: In the "colliding mice" sample, a mouse coordiantes system is yaxis = nose to tail axis: combining with the mouse item rotation, a mouse does not only go down, but in the good direction
Perhaps, "The Graphics View Coordinate System":http://qt-project.org/doc/qt-4.8/graphicsview.html#the-graphics-view-coordinate-system can help...
-
Thanks sraboisson! Wonderful explanation. Ah so 'increment' part comes from mapToParent as you showed in the code. I think the reason it did not occur to me was I didn't think the origin changed everytime setpos(mapToParent(..)) was called.