This is what I tried, it gave me no output. Where am I going wrong?
// Start point of bottom line
qreal startPointX1 = 600.0;
qreal startPointY1 = 600.0;
// End point of bottom line
qreal endPointX1 = 600.0;
qreal endPointY1 = 1200.0;
// Start point of top line
qreal startPointX2 = 600.0;
qreal startPointY2 = 600.0;
// End point of top line
qreal endPointX2 = 800.0;
qreal endPointY2 = 1200.0;
QPainterPath path;
// Set pen to this point.
path.moveTo (startPointX1, startPointY1);
// Draw line from pen point to this point.
path.lineTo (endPointX1, endPointY1);
path.moveTo (endPointX1, endPointY1);
path.lineTo (endPointX2, endPointY2);
path.moveTo (endPointX2, endPointY2);
path.lineTo (startPointX1, startPointY1);
painter.setPen (Qt :: NoPen);
painter.fillPath (path, QBrush (QColor ("blue")));
I have just tried to create a path between these 3 points and fill the area, but there is no output shown.
If you want use QRectF
QRectF rect = QRectF(0, 0, 100, 100);
QPainterPath path;
path.moveTo(rect.left() + (rect.width() / 2), rect.top());
path.lineTo(rect.bottomLeft());
path.lineTo(rect.bottomRight());
path.lineTo(rect.left() + (rect.width() / 2), rect.top());
painter.fillPath(path, QBrush(QColor ("blue")));
I think you do not need to call moveTo()
function after you call lineTo()
because the current position already updated to the the end point of the line you draw. Here is the code that draws a rectangle for me:
// Start point of bottom line
qreal startPointX1 = 600.0;
qreal startPointY1 = 600.0;
// End point of bottom line
qreal endPointX1 = 600.0;
qreal endPointY1 = 1200.0;
// Start point of top line
qreal startPointX2 = 600.0;
qreal startPointY2 = 600.0;
// End point of top line
qreal endPointX2 = 800.0;
qreal endPointY2 = 1200.0;
QPainterPath path;
// Set pen to this point.
path.moveTo (startPointX1, startPointY1);
// Draw line from pen point to this point.
path.lineTo (endPointX1, endPointY1);
//path.moveTo (endPointX1, endPointY1); // <- no need to move
path.lineTo (endPointX2, endPointY2);
//path.moveTo (endPointX2, endPointY2); // <- no need to move
path.lineTo (startPointX1, startPointY1);
painter.setPen (Qt :: NoPen);
painter.fillPath (path, QBrush (QColor ("blue")));
The documentation says: "Moving the current point will also start a new subpath (implicitly closing the previously current path when the new one is started)".
This means you should once move to the origin of the path, then use only lineTo in order to draw the shape to be filled.
I added this answer because the answer "I think you do not need to call moveTo() function after you call lineTo() because the current position already updated to the the end point of the line you draw." is quite misleading. The moveTo is not unnecessary, it's actually causing the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With