How to draw and fill a triangle with QPainter?

Aquarius_Girl picture Aquarius_Girl · Oct 14, 2013 · Viewed 20.5k times · Source

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.

Answer

vahancho picture vahancho · Oct 14, 2013

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