Qt如何实现QTableView的撤消与恢复功能 转载

http://hi.baidu.com/topone_top/item/3d8221f1d9fb6d0aa62988b7
1、实现TableView上的撤消与恢复功能,首先需一个类来继承QUndoCommand类,并且在继承类中实现redo()函数与undo()函数。
也就是具体的撤消与恢复功能都是在这两个函数中实现的。
例如:
class DeleteCommand:public QUndoCommand
{
public:
 DeleteCommand(SqlModel *,QVector<QModelIndex>, QVector<QVariant>, 
             QVector<QVariant>,QUndoCommand *parent = 0);
 void undo();
 void redo();
 void Clear();
private:
 QVector<QModelIndex> m_modelIndexs;
 QVector<QVariant> m_editedDatas;
 QVector<QVariant> m_orignlDatas;
 SqlModel * m_model;
};
DeleteCommand::DeleteCommand(SqlModel * model, 
 QVector<QModelIndex> ins, QVector<QVariant> ed, 
 QVector<QVariant> od, QUndoCommand *parent )
 :QUndoCommand(parent)
{
 m_model = model;
 m_modelIndexs = ins;
 m_editedDatas = ed;
 m_orignlDatas = od;
}
void DeleteCommand::undo()
{
 for(int i = 0; i < m_modelIndexs.count(); i ++)
 {
  m_model->setData(m_modelIndexs.at(i), m_orignlDatas.at(i), Qt::EditRole);
 }
}
void DeleteCommand::redo()
{
 for(int i = 0; i < m_modelIndexs.count(); i ++)
 {
  m_model->setData(m_modelIndexs.at(i), m_editedDatas.at(i), Qt::EditRole);
 }
}
2、调用派生类。
主要代码如下:
QUndoStack  undoStack = new QUndoStack(); 
   QAction *  undoAction = undoStack->createUndoAction(this, tr("&Undo"));
    undoAction->setShortcut(tr("Ctrl + Z"));  
    QACtion * redoAction = undoStack->createRedoAction(this, tr("&Redo"));
   redoAction->setShortCut(tr("Ctrl + Y"));
 DeleteCommand * deleteCommand = new DeleteCommand(m_sqlmodel, indexVec, editedVec, orginVec);
    undoStack->push(deleteCommand );
通过undoStack来创建ACtion,将两者联系起来。就可以实现撤消与删除的功能了。
 3、另外说明
如果是多窗口则需要用QUndoGroup
每个窗口用一个QUndoStack
每个命令用一个QUndoCommand
自己实现QUndoCommand的子类,并且重新实现redo和undo函数即可
 
当然,也可以参照Qt自带的例子。
#Qt

你可能感兴趣的:(Qt如何实现QTableView的撤消与恢复功能 转载)