PDA

View Full Version : How can a QGraphicsRectItem get the coordinate of its top left corner?



blooglet
13th February 2011, 19:29
How can a QGraphicsRectItem retrieve the coordinate of its top left corner, relative to the scene it is associated with? I tried working with boundingRect().x(), but these coordinates are outdated after the item is dragged across the scene. scenePos().x() always returns 0 for some reason.

I'm asking because I want to implement my own mousePressEvent on a class that derives from QGraphicsRectItem. I need to know if the user clicked in a corner of the rectangle or not so that I can allow the shape to be resized using selection grips.

wysota
13th February 2011, 19:47
scenePos().x() returns 0 because you specified the item's rectangle in scene coordinates instead of its local coordinates. Thus you have placed the item in its desired position not by moving the item in its appropriate place with setPos(). In either case mapToScene(boundingRect().topLeft()) will return the value you want bur you should first consider if you created the item correctly in the first place.

blooglet
13th February 2011, 20:03
The initializer list of the offending object contains a call to QGraphicsRectItem(x, y, width, height) where x and y are scene coordinates. Is this the wrong way to do it? The doc (http://doc.qt.nokia.com/4.7/qgraphicsrectitem.html) for QGraphicsRectItem is a little vague about this.

The only other place where I modify the item's rectangle is when the user wants to change the rectangle's width and the height is changed proportionally:
this->setRect(this->rect().x(), this->rect().y(), width, width/WH_RATIO);

wysota
13th February 2011, 20:11
The initializer list of the offending object contains a call to QGraphicsRectItem(x, y, width, height) where x and y are scene coordinates. Is this the wrong way to do it? The doc (http://doc.qt.nokia.com/4.7/qgraphicsrectitem.html) for QGraphicsRectItem is a little vague about this.
It depends what you mean by "wrong". Usually you'd want a rectangle that starts in (0,0) and expands to the right and down (i.e. has positive width and height) but specifying some other rectangle might be ok too in some situations.

blooglet
13th February 2011, 20:24
You helped uncover some oddities in my code... my derivative of QGraphicsRectItem had a constructor that took the desired scene coordinates and passed them to the constructor of QGraphicsRectItem. Then I remembered that Qt's built-in graphic items didn't do that and the caller had to use newGraphicsItem->setPos() to set the position. I updated my code to fix this illogical behavior.

Thanks for your help!