QT开发中文网

qt QGraphicsView 橡皮檫工具 c++ 代码

以下是一个简单的Qt QGraphicsView橡皮擦工具C++代码示例:

  1. 首先,您需要在Qt Creator中创建一个新的Qt Widgets应用程序项目,并添加一个QGraphicsView小部件。

  2. 在您的主窗口头文件中,添加以下包含语句和前置声明:

#include <QGraphicsScene>
#include <QGraphicsView>

class QMouseEvent;
class QPainterPath;
  1. 然后,在主窗口类中声明以下私有成员变量:
private:
    bool m_isDrawing;            // 是否正在绘制
    QPointF m_lastPos;           // 上一次鼠标位置
    QPainterPath* m_path;        // 绘制路径
    QGraphicsScene* m_scene;     // 场景对象
  1. 在您的主窗口构造函数中初始化这些变量,并设置场景为QGraphicsView的场景:
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    m_isDrawing = false;
    m_lastPos = QPointF();
    m_path = new QPainterPath();

    m_scene = new QGraphicsScene(this);
    ui.graphicsView->setScene(m_scene);
}
  1. 接下来,重写鼠标事件处理程序以响应用户输入。在鼠标按下事件中,开始绘制路径并将m_isDrawing设置为true。在鼠标移动事件中,更新路径并重新绘制场景。在释放鼠标事件中,停止绘制路径并将m_isDrawing设置为false。
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_lastPos = event->pos();
        m_path->moveTo(m_lastPos);
        m_isDrawing = true;
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons() & Qt::LeftButton) && m_isDrawing) {
        QPointF newPos = event->pos();
        qreal dx = newPos.x() - m_lastPos.x();
        qreal dy = newPos.y() - m_lastPos.y();

        if (dx * dx + dy * dy > 5.0) {      // 避免过度绘制
            m_path->lineTo(newPos);
            m_scene->addPath(*m_path);
            m_lastPos = newPos;
        }
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_isDrawing) {
        QPointF newPos = event->pos();
        qreal dx = newPos.x() - m_lastPos.x();
        qreal dy = newPos.y() - m_lastPos.y();

        if (dx * dx + dy * dy > 5.0) {      // 避免过度绘制
            m_path->lineTo(newPos);
            m_scene->addPath(*m_path);
            m_path->~QPainterPath();         // 清空路径对象
            new(m_path) QPainterPath;       // 重新分配新的路径对象
            ui.graphicsView->viewport()->update();   // 更新视口以清除残留的轨迹
        }

        m_isDrawing = false;
    }
}
  1. 最后,您可以添加一些其他功能,例如设置画笔颜色和宽度:
void MainWindow::on_colorButton_clicked()
{
    QColor color = QColorDialog::getColor(Qt::black, this);
    if (color.isValid()) {
        QPen pen(color, ui.widthSpinBox->value());
        m_path->setPen(pen);
    }
}

void MainWindow::on_widthSpinBox_valueChanged(int value)
{
    QPen pen(m_path->pen().color(), value);
    m_path->setPen(pen);
}

这是一个非常基本的Qt QGraphicsView橡皮擦工具C++代码示例。您可以根据需要对其进行修改和扩展。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://qt.0voice.com/?id=1972

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?