c++ qtreewidget支持撤销与恢复功能 代码
时间: 2024-01-01 19:06:48 浏览: 76
QTreeWidget的增与删的基本的操作
Qt的QTreeWidget没有自带的撤销与恢复功能,但是我们可以结合QUndoStack来实现。
以下是一个简单的示例代码:
```
#include <QtWidgets>
class TreeWidget : public QTreeWidget
{
Q_OBJECT
public:
TreeWidget(QWidget *parent = nullptr);
public slots:
void addItem();
void removeItem();
void undo();
void redo();
private:
QUndoStack *m_undoStack;
};
TreeWidget::TreeWidget(QWidget *parent)
: QTreeWidget(parent)
{
// 创建撤销栈
m_undoStack = new QUndoStack(this);
// 添加菜单项
QAction *addItemAction = new QAction(tr("&Add Item"), this);
connect(addItemAction, &QAction::triggered, this, &TreeWidget::addItem);
addAction(addItemAction);
QAction *removeItemAction = new QAction(tr("&Remove Item"), this);
connect(removeItemAction, &QAction::triggered, this, &TreeWidget::removeItem);
addAction(removeItemAction);
// 添加撤销和恢复菜单项
QAction *undoAction = m_undoStack->createUndoAction(this, tr("&Undo"));
undoAction->setShortcuts(QKeySequence::Undo);
QAction *redoAction = m_undoStack->createRedoAction(this, tr("&Redo"));
redoAction->setShortcuts(QKeySequence::Redo);
addAction(undoAction);
addAction(redoAction);
}
void TreeWidget::addItem()
{
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << tr("Item"));
m_undoStack->push(new QTreeWidgetItemRemovedCommand(this, item));
}
void TreeWidget::removeItem()
{
QTreeWidgetItem *item = currentItem();
if (item) {
m_undoStack->push(new QTreeWidgetItemAddedCommand(this, item));
delete item;
}
}
void TreeWidget::undo()
{
m_undoStack->undo();
}
void TreeWidget::redo()
{
m_undoStack->redo();
}
// 定义命令类
class QTreeWidgetItemAddedCommand : public QUndoCommand
{
public:
QTreeWidgetItemAddedCommand(QTreeWidget *treeWidget, QTreeWidgetItem *item)
: m_treeWidget(treeWidget), m_item(item)
{
setText(tr("Add Item"));
}
void undo() override
{
m_treeWidget->removeItemWidget(m_item);
}
void redo() override
{
m_treeWidget->addTopLevelItem(m_item);
}
private:
QTreeWidget *m_treeWidget;
QTreeWidgetItem *m_item;
};
class QTreeWidgetItemRemovedCommand : public QUndoCommand
{
public:
QTreeWidgetItemRemovedCommand(QTreeWidget *treeWidget, QTreeWidgetItem *item)
: m_treeWidget(treeWidget), m_item(item)
{
setText(tr("Remove Item"));
}
void undo() override
{
m_treeWidget->addTopLevelItem(m_item);
}
void redo() override
{
m_treeWidget->removeItemWidget(m_item);
}
private:
QTreeWidget *m_treeWidget;
QTreeWidgetItem *m_item;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TreeWidget treeWidget;
treeWidget.show();
return app.exec();
}
#include "main.moc"
```
在这个示例代码中,我们创建了一个TreeWidget类继承自QTreeWidget,并在其中添加了撤销和恢复功能。我们使用QUndoStack来管理所有的撤销和恢复操作,并在addItem和removeItem槽函数中创建并添加相应的命令类。
每次执行addItem或removeItem时,我们都会在撤销栈中添加对应的命令类,并在undo和redo槽函数中执行相应的撤销和恢复操作。
注意,在添加或删除QTreeWidgetItem时,我们需要使用QTreeWidget的addItem和removeItemWidget函数,而不是QTreeWidgetItem的addChild和removeChild函数。这是因为QTreeWidgetItem的addChild和removeChild函数并不会将它从它的父项中移除,而只是从它的父项的子项列表中移除。这可能会导致撤销和恢复操作出现问题。
阅读全文