6

I am drawing a line using QPainterPath between 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 have defined bounding rect as:

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

I get line painted correctly when:

start_p.x() < end_p.x() 

and

start_p.y() < end_p.y()

How should the bounding rect be defined so that line is drawn correctly irrespective of the relationship between the coordinates of two points(start_p and end_p)?

Kamalpreet Grewal
  • 822
  • 1
  • 13
  • 28

3 Answers3

7

You might try to normalize your rectangle:

QRectF Line::boundingRect() const
{
    return QRectF(start_p.x(), start_p.y(), end_p.x(), end_p.y()).normalized();
}
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • The arguments to this version of QRectF's constructor (https://doc.qt.io/qt-5/qrectf.html#QRectF-3) are x, y, width, and height. Shouldn't it be `QRectF(start_p, end_p)` (https://doc.qt.io/qt-5/qrectf.html#QRectF-2)? – Mitch Dec 04 '21 at 15:21
  • @Mitch, right, it might be `QRectF(start_p, end_p)` too. – vahancho Dec 06 '21 at 07:24
3

You could either:-

  • Check for the conditions when the ends are greater than the start points and set the rect appropriately
  • Return the QPainterPath's bounding rect
  • Use a QGraphicsLineItem instead of reinventing the wheel.

If you just want a line, QGraphicsLineItem is likely the best way to go here.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
0

You can use QPainterPath::boundingRect which returns the bounding rectangle of the QPainterPath. You can keep the painter path as a class member and access it in the boundingRect function :

QRectF Line::boundingRect() const
{
     return line.boundingRect();
}
Nejat
  • 31,784
  • 12
  • 106
  • 138