qt绘制曲线

#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(pointsi);

// 绘制点

painter.setPen(Qt::NoPen);

painter.setBrush(Qt::red);

painter.drawEllipse(pointsi, 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();

相关推荐
xcyxiner5 小时前
DicomViewer24 修复编译bug(window test 失败)
前端·qt
sycmancia11 小时前
Qml——Rectangle元素
qt
sycmancia14 小时前
Qml——Item元素
qt
励志不掉头发的内向程序员15 小时前
【从零写一个CAD 04】中键拖动平移:抓住一个点,让它一直待在鼠标底下
开发语言·c++·qt·学习·系统架构·计算机外设
zhanghaha13141 天前
Qt 中的类是什么?保姆级详解(新手版)
qt
看看我呀看看我1 天前
基于Qt的虚拟键盘
c++·qt·qt5·qt6.3
kaixin_learn_qt_ing1 天前
Qt抽屉窗体实现demo
开发语言·qt
huanbailu1 天前
Qt 跨线程信号槽:connect 返回 true 但槽函数不执行的坑
开发语言·c++·qt·信号槽·跨线程·元类型
Quz2 天前
QML SplitView:可拖拽分隔面板与自定义 Handle
qt
Quz2 天前
QML SplitView 进阶:嵌套布局与状态持久化
qt