如何用QPainter绘制和填充三角形?

Aqu*_*irl 7 qt qpainter

这是我试过的,它没有给我输出.我哪里错了?

      // 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")));
Run Code Online (Sandbox Code Playgroud)

我刚刚尝试在这3个点之间创建一条路径并填充该区域,但没有显示输出.

vah*_*cho 14

我认为你打电话moveTo()后不需要调用函数,lineTo()因为当前位置已经更新到你绘制的线的终点.这是为我绘制矩形的代码:

// 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")));
Run Code Online (Sandbox Code Playgroud)


Ser*_*ral 6

如果你想使用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")));
Run Code Online (Sandbox Code Playgroud)

  • 2021 年仍然表现出色 (2认同)