WhiteBoard::WhiteBoard(QWidget *parent) : QWidget(parent), ui(new Ui::WhiteBoard) { ui->setupUi(this); setMouseTracking(true); } void WhiteBoard::mousePressEve...-QT开发中文网" />

QT开发中文网

#include "whiteboard.h" #include "ui_whiteboard.h" #include WhiteBoard::WhiteBoard(QWidget *parent) : QWidget(parent), ui(new Ui::WhiteBoard) { ui->setupUi(this); setMouseTracking(true); } void WhiteBoard::mousePressEve...

要实现undo和redo功能,您可以在WhiteBoard类中添加一些成员变量和方法来跟踪绘图操作的历史记录。以下是一个可能的实现示例:

在WhiteBoard类的私有部分添加以下成员变量:

QList<QPainterPath> paths; // 保存绘图路径的历史记录
int currentPathIndex; // 当前绘图路径的索引

在WhiteBoard类的构造函数中进行初始化:

WhiteBoard::WhiteBoard(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WhiteBoard)
{
    ui->setupUi(this);
    setMouseTracking(true);

    currentPathIndex = -1;
}

修改mousePressEvent()方法,在每次新绘制一条路径时清除之后的历史记录:

void WhiteBoard::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        path.moveTo(event->pos());
        paths.erase(paths.begin() + currentPathIndex + 1, paths.end()); // 清除当前路径之后的历史记录
        ++currentPathIndex;
        paths.append(path); // 将当前路径添加到历史记录中
        update();
    }
}

修改paintEvent()方法,只绘制当前路径以及之前的所有路径:

void WhiteBoard::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.fillRect(rect(), Qt::white);
    
    for (int i = 0; i <= currentPathIndex; ++i)
    {
        painter.setPen(Qt::black);
        painter.drawPath(paths[i]);
    }
}

添加undo和redo方法:

void WhiteBoard::undo()
{
    if (currentPathIndex >= 0)
    {
        --currentPathIndex;
        update();
    }
}

void WhiteBoard::redo()
{
    if (currentPathIndex < paths.size() - 1)
    {
        ++currentPathIndex;
        update();
    }
}

现在,您可以将undo和redo功能与按钮或其他交互元素连接起来,调用对应的undo()和redo()方法即可实现撤销和重做操作。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处: WhiteBoard::WhiteBoard(QWidget *parent) : QWidget(parent), ui(new Ui::WhiteBoard) { ui->setupUi(this); setMouseTracking(true); } void WhiteBoard::mousePressEve...">https://qt.0voice.com/?id=11861

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

还没有评论,快来说点什么吧~

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?