PDA

View Full Version : displaying a QRect item perpendicular to its parent QGraphicsLineItem on the scene.



jeevan_ravula
4th May 2014, 12:00
I have a QGraphicsLineItem on the scene. This line item can be rotated on the scene using either of its end points as an anchor. Basically this line can rotated and resized. I want to draw a rectangle such that it always intersects the parent line at 90 degrees. The rectangle should remain perpendicular to the line at any given instant.
The rectangle's points topLeft, topRight should lie on one side of the line while bottomLeft & bottomRight should lie on the other side of the line. I tried the below code but the rectangle does not render itself perpendicular to the line.


void PersonSizeGraphicsItem::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{

CustomGraphicsLineItem* parent_line_item = dynamic_cast<CustomGraphicsLineItem *>(parent_item);
if(parent_line_item == NULL)
{
return;
}

QPen myPen = parent_line_item->pen();
myPen.setColor(Qt::red);
painter->setPen(myPen);
painter->setRenderHint(QPainter::Antialiasing);

QLineF parent_line = parent_line_item->line();
QLineF normal_vector_line = parent_line.normalVector();
normal_vector_line.setLength(30.0);

QPointF first_line_base_point = parent_line.pointAt(0.4);

QPointF _p1 = first_line_base_point -(normal_vector_line.p1()-normal_vector_line.p2());
QPointF _p2 = first_line_base_point +(normal_vector_line.p1()-normal_vector_line.p2());

QLineF rect_line_one = normal_vector_line;
rect_line_one.setP1(_p1);
rect_line_one.setP2(_p2);

QPointF second_line_base_point = parent_line.pointAt(0.7);

QPointF _p3 = second_line_base_point -(normal_vector_line.p1()-normal_vector_line.p2());
QPointF _p4 = second_line_base_point +(normal_vector_line.p1()-normal_vector_line.p2());

QLineF rect_line_two = normal_vector_line;
rect_line_two.setP1(_p3);
rect_line_two.setP2(_p4);

//QRect image_rect( rect_line_one.p1().toPoint(), QSize(30, 60));
QRect image_rect;
image_rect.setTopLeft( rect_line_one.p1().toPoint());
//image_rect.setBottomLeft( rect_line_one.p2().toPoint());
//image_rect.setTopRight(rect_line_two.p1().toPoint( ));
image_rect.setBottomRight(rect_line_two.p2().toPoi nt());

painter->drawRect(image_rect);

//painter->drawLine(rect_line_one);
//painter->drawLine(rect_line_two);
//painter->drawImage(image_rect, source_image);
}