#pragma once
#include <QWidget>
#include <QPainter>
#include <QPainterPath>
#include <QMouseEvent>
#include <QVector>
class CurveWidget : public QWidget {
Q_OBJECT
public:
CurveWidget(QWidget* parent = nullptr) : QWidget(parent), lastPoint(QPointF()) {}
protected:
void mousePressEvent(QMouseEvent* event) override {
if (event->button() == Qt::LeftButton) {
lastPoint = event->pos();
points.clear();
points.append(lastPoint);
update();
}
}
void mouseMoveEvent(QMouseEvent* event) override {
if (event->buttons() & Qt::LeftButton) {
QPointF newPoint = event->pos();
if ((newPoint - lastPoint).manhattanLength() > 0) { // 避免绘制过于密集的点
points.append(newPoint);
lastPoint = newPoint;
update();
}
}
}
void paintEvent(QPaintEvent* event) override {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
if (!points.isEmpty()) {
path.moveTo(points.first());
for (int i = 1; i < points.size(); ++i) {
// 这里我们仍然使用lineTo来连接点,但为了视觉效果,你可以在最终渲染时应用平滑算法
path.lineTo(points[i]);
// 绘制点
painter.setPen(Qt::NoPen);
painter.setBrush(Qt::red);
painter.drawEllipse(points[i], 3, 3); // 绘制以点为中心,半径为3的小圆
}
// 如果需要绘制平滑曲线,这里应该使用cubicTo或quadTo,并计算控制点
painter.setPen(QPen(Qt::blue, 2));
painter.setBrush(Qt::transparent);
painter.drawPath(path);
}
}
private:
QVector<QPointF> points;
QPointF lastPoint;
};
// 使用方法同前
// CurveWidget *widget = new CurveWidget();
// widget->show();