要实现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助手提供,问题来源于学员提问