• 实现思路

实现一个**QCPItemPolygon** 继承于QCPAbstractItem

// 头文件部分
class QCPItemPolygon : public QCPAbstractItem
{
  Q_OBJECT
public:
  explicit QCPItemPolygon(QCustomPlot *parentPlot);
     double selectTest(const QPointF&, bool, QVariant*) const override { return 0; }
  virtual ~QCPItemPolygon() {}
  
  // 设置真实的点信息
   void setPoints(const QVector<QPointF>& vecPoint);

  // Define position types
  QCPItemPosition * const topLeft;
  QCPItemPosition * const topRight;
  QCPItemPosition * const bottomLeft;
  QCPItemPosition * const bottomRight;

  // Define the polygon vertices
  QVector<QPointF> vertices;

protected:
  virtual void draw(QCPPainter *painter) override;
  virtual QPointF anchorPixelPosition(int anchorId) const override;
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

实现Cpp部分

QCPItemPolygon::QCPItemPolygon(QCustomPlot *parentPlot) :
  QCPAbstractItem(parentPlot),
  topLeft(createPosition("topLeft")),
  topRight(createPosition("topRight")),
  bottomLeft(createPosition("bottomLeft")),
  bottomRight(createPosition("bottomRight"))
{
  topLeft->setCoords(0, 1);
  topRight->setCoords(1, 1);
  bottomLeft->setCoords(0, 0);
  bottomRight->setCoords(1, 0);

 // 此处填写真实的坐标!
  vertices << QPointF(-71.8,5.2) << QPointF(-68.2,-5.2) << QPointF(6.7, 4.9) << QPointF(3.1 ,15.3);
}

void QCPItemPolygon::draw(QCPPainter *painter)
{
  if (vertices.isEmpty())
    return;

  QPolygonF polygon;
  for (const QPointF &vertex : vertices)
  {
    double x = bottomLeft->pixelPosition().x() + vertex.x() * (bottomRight->pixelPosition().x() - bottomLeft->pixelPosition().x());
    double y = bottomLeft->pixelPosition().y() + vertex.y() * (topLeft->pixelPosition().y() - bottomLeft->pixelPosition().y());
    polygon << QPointF(x, y);
  }

  painter->setPen(Qt::black);  // Set the pen color as needed
  painter->setBrush(QBrush(QColor("pink")));  // Set the brush  if needed
  painter->drawPolygon(polygon);
}

QPointF QCPItemPolygon::anchorPixelPosition(int anchorId) const
{
  Q_UNUSED(anchorId)
  return QPointF();
}

void QCPItemPolygon::setPoints(const QVector<QPointF> &vecPoint)
{
    vertices.clear();
    vertices = vecPoint;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.

调用方式:

QCPItemPolygon* ply = new QCPItemPolygon(customPlot); //
 customPlot->replot(); // 唤起Replot方法
  • 1.
  • 2.