Important: Please read the Qt Code of Conduct -

[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:
    QRectF Move::boundingRect() const
    QLineF line(from->pos(),to->pos());
    qreal lenght = line.length();
    qreal sin = (to->pos().y()-from->pos().y())/lenght;
    qreal cos = (to->pos().x()-from->pos().x())/lenght;
    QPointF fromPoint, toPoint;
    toPoint. setX(to ->pos().x()-to ->width()/2cos);
    toPoint. setY(to ->pos().y()-to ->width()/2
    return QRectF(fromPoint,toPoint);

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

    QPointF vec;
    vec = to->pos() - from->pos();

    // normalize the vector
    QPointF vecNorm /= (vec.x() * vec.x() + vec.y() * vec.y());

    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)

Log in to reply