抱歉,之前给出的代码有误。在QPainterPath中没有直接将QList
#include <QtWidgets>
class CustomWidget : public QWidget {
public:
CustomWidget(QWidget *parent = nullptr) : QWidget(parent), drawing(false) {
setMouseTracking(true);
}
protected:
void paintEvent(QPaintEvent *event) override {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 2));
for (const QList<QPointF>& curve : curves) {
if (curve.size() >= 2) {
QPainterPath path;
path.moveTo(curve.first());
for (int i = 1; i < curve.size(); ++i) {
path.lineTo(curve[i]);
}
painter.drawPath(path);
}
}
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
currentCurve.clear();
currentCurve.append(event->pos());
drawing = true;
update();
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if (drawing && event->buttons() & Qt::LeftButton) {
currentCurve.append(event->pos());
update();
}
}
void mouseReleaseEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton && drawing) {
currentCurve.append(event->pos());
// Apply the Bezier algorithm to smooth the curve
QList<QPointF> smoothedCurve = bezierAlgorithm(currentCurve);
// Add the smoothed curve to the list of curves
curves.append(smoothedCurve);
// Clear the current curve and finish drawing
currentCurve.clear();
drawing = false;
update();
}
}
private:
QList<QList<QPointF>> curves;
QList<QPointF> currentCurve;
bool drawing;
QList<QPointF> bezierAlgorithm(const QList<QPointF>& points, int resolution = 50) {
QList<QPointF> smoothedCurve;
if (points.size() < 2) {
return smoothedCurve;
}
for (int i = 0; i <= resolution; ++i) {
qreal t = static_cast<qreal>(i) / resolution;
QPointF point;
for (int j = 0; j < points.size(); ++j) {
qreal coefficient = binomialCoefficient(points.size() - 1, j);
qreal term = coefficient * qPow(t, j) * qPow(1 - t, points.size() - 1 - j);
point += term * points[j];
}
smoothedCurve.append(point);
}
return smoothedCurve;
}
int binomialCoefficient(int n, int k) const {
if (k > n)
return 0;
int result = 1;
for (int i = 0; i < k; ++i) {
result *= (n - i);
result /= (i + 1);
}
return result;
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
CustomWidget widget;
widget.resize(800, 600);
widget.show();
return app.exec();
}
这样应该可以正常编译和运行了。如果还有其他问题,请随时提问!
内容由零声教学AI助手提供,问题来源于学员提问