10

这是我尝试过的,它没有给我任何输出。我哪里错了?

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

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

4

3 回答 3

18

我认为您不需要在调用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")));
于 2013-10-14T09:11:10.810 回答
10

如果你想使用 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")));
于 2014-09-30T19:06:01.757 回答
1

文档说:“移动当前点也将启动一个新的子路径(在启动新路径时隐式关闭先前的当前路径)”。

这意味着您应该移动到路径的原点,然后只使用 lineTo 来绘制要填充的形状。

我添加了这个答案,因为答案“我认为你不需要在调用 lineTo() 后调用 moveTo() 函数,因为当前位置已经更新到你绘制的线的终点。” 很有误导性。moveTo 不是不必要的,它实际上是导致问题的原因。

于 2017-08-14T19:52:40.330 回答