May 4, 2012

soroush soroush
Lab Rat
660 posts

[SOLVED] Select a QGraphicsItem in a scene


Hi forum

I have a problem with my QGraphicsItem derived objects. They are not selectable in all situations. I guess its because of their bounding rect, which I simply return by calling ctor of QRectF and giving two points as corners. Is bounding rectangle supposed to have correct topleft and bottom-right points?

In the following image the link from B to C is selectable and there in no problem but link from A to B is not selectable.
If I move state B down, A to B is selectable and B to C can not be selected:

The bounding rectangle of both is calculated like this:

  1. QRectF Move::boundingRect() const
  2. {
  3.     QLineF line(from->pos(),to->pos());
  4.     qreal lenght = line.length();
  5.     qreal sin = (to->pos().y()-from->pos().y())/lenght;
  6.     qreal cos = (to->pos().x()-from->pos().x())/lenght;
  7.     QPointF fromPoint, toPoint;
  8.     fromPoint.setX(from->pos().x()+from->width()/2*cos);
  9.     fromPoint.setY(from->pos().y()+from->width()/2*sin);
  10.     toPoint.  setX(to  ->pos().x()-to  ->width()/2*cos);
  11.     toPoint.  setY(to  ->pos().y()-to  ->width()/2*sin);
  12.     return QRectF(fromPoint,toPoint);
  13. }

1 reply

May 7, 2012

rschaub rschaub
Lab Rat
33 posts

the bounding rect should always be calculated in local coordinates.
In your case, fromPoint should be (0, 0) and toPoint would equal to

  1. QPointF vec;
  2. vec = to->pos() - from->pos();
  4. // normalize the vector
  5. QPointF vecNorm /= (vec.x() * vec.x() + vec.y() * vec.y());
  7. toPoint = vec - vecNorm * to->width();

(that is, assuming your circles and lines don’t have different scaling matrices, else you’d have to calculate their radii in line-local coordinates)

  ‹‹ Qt Applications using the serial port?      showing content of a file in the tabs ››

You must log in to post a reply. Not a member yet? Register here!