如何在任何实例中绘制一个垂直于其父QGraphicsLineItem显示的矩形

时间:2014-05-04 10:14:30

标签: qt qgraphicsitem

我在场景中有一个QGraphicsLineItem。此订单项可以使用其任一端点作为锚点在场景中旋转。基本上这条线可以旋转和调整大小。我想绘制一个矩形,使其始终与父线相交90度。在任何给定的瞬间,矩形应保持垂直于线。矩形的顶部左侧,顶部右侧应位于线的一侧,而底部左侧和右侧。 bottomRight应该位于该行的另一侧。我尝试了下面的代码,但矩形不会使自己垂直于线。实际上,我打算显示垂直于线条的矩形图像,此图像也可以调整大小。我非常需要做到这一点。任何人都可以回答这个问题吗?

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().toPoint());

    painter->drawRect(image_rect);

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

0 个答案:

没有答案