Define a bounding rectangle of a line in Qt

I draw a line using QPainterPathbetween two points as follows:

QPainterPath line;
line.moveTo(start_p);
line.lineTo(end_p);

QPen paintpen(Qt::black);
paintpen.setWidth(1);
painter->setRenderHint(QPainter::Antialiasing);
painter->setBrush(Qt::SolidPattern);
painter->setPen(paintpen);
painter->drawPath(line);

I defined the bounding box as:

QRectF Line::boundingRect() const
{
 return QRectF(start_p.x(), start_p.y(), end_p.x(), end_p.y());
}

I draw the line correctly when:

start_p.x() < end_p.x() 

and

start_p.y() < end_p.y()

How to define a bounding box so that the line is drawn correctly regardless of the relationship between the coordinates of the two points (start_p and end_p)?

+4
source share
3 answers

You can try to normalize your rectangle:

QRectF Line::boundingRect() const
{
    return QRectF(start_p.x(), start_p.y(), end_p.x(), end_p.y()).normalized();
}
+7
source

You can: -

  • Check the conditions when the ends are larger than the starting points, and set the rectangle correctly
  • Returns the bounding box of QPainterPath
  • QGraphicsLineItem , .

, QGraphicsLineItem, , .

+2

You can use QPainterPath::boundingRectthat returns the bounding box QPainterPath. You can save the artist’s path as a member of the class and access it in a function boundingRect:

QRectF Line::boundingRect() const
{
     return line.boundingRect();
}
0
source

All Articles