在Qt中撤消重做

时间:2014-07-22 18:09:52

标签: c++ qt

我在我的Qt applocation中添加了一个图形视图,其中可以添加不同的项目,如line,ellipse如何在图形视图中应用撤消重做操作。以下是添加行等项目的代码。 mainwindow.cpp

connect(ui->lineButton, SIGNAL(clicked()), this, SLOT(drawLine()));

line.cpp

void line::mousePressEvent(QGraphicsSceneMouseEvent* e){
    if(e->button()==Qt::LeftButton) {
        if(mFirstClick){
            x1 = e->pos().x();
            y1 = e->pos().y();
            mFirstClick = false;
            mSecondClick = true;
        }

        else if(!mFirstClick && mSecondClick){
            x2 = e->pos().x();
            y2 = e->pos().y();
            mPaintFlag = true;
            mSecondClick = false;
            update();
        }
    }
    QGraphicsItem::mousePressEvent(e);
    update();
}

void line:: paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    QRectF rect = boundingRect();
    if(mPaintFlag){
        QPen paintpen(Qt::red);
        paintpen.setWidth(4);

        QPen linepen(Qt::black);
        linepen.setWidth(1);

        QPoint p1;
        p1.setX(x1);
        p1.setY(y1);

        painter->setPen(paintpen);
        painter->drawPoint(p1);

        QPoint p2;
        p2.setX(x2);
        p2.setY(y2);

        painter->setPen(paintpen);
        painter->drawPoint(p2);

        painter->setPen(linepen);
        painter->drawLine(p1, p2);
    }
}

void line::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
    if (e->modifiers() & Qt::ShiftModifier) {
        stuff << e->pos();
        update();
        return;
    }
    QGraphicsItem::mouseMoveEvent(e);
}

void line::mouseReleaseEvent(QGraphicsSceneMouseEvent *e)
{
    QGraphicsItem::mouseReleaseEvent(e);
    update();
}

drawLine slot

 void MainWindow::drawLine(){
    ui->graphicsView->setScene(scene);
    line *item = new line;
    scene->addItem(item);
    qDebug() << "Line Created";

}

编辑:

void MainWindow::on_actionUndo_triggered()
    {
        undoView = new QUndoView(undoStack);
       ui->actionUndo= undoStack->createUndoAction(this, tr("&Undo"));
     ui->actionUndo->setShortcuts(QKeySequence::Undo);
}

1 个答案:

答案 0 :(得分:1)

您可以继续在应用程序中实现命令模式。这是The Gang of Four 设计模式:可重用面向对象软件的元素一书中的模式。我认为可以在这里找到一个比我对模式更好的解释:Command Pattern

虽然这篇文章专注于游戏,但您也可以将它应用到您的代码中。祝你好运!