- 实现思路
实现一个**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;
};
实现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;
}
调用方式:
QCPItemPolygon* ply = new QCPItemPolygon(customPlot); //
customPlot->replot(); // 唤起Replot方法