How to draw and fill a triangle with QPainter?

感情迁移 提交于 2019-12-03 14:40:02

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")));
Sergio Cabral

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")));

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!