Qt之QTreeWidget通过撤销栈移除item
本文记录QTreeWidget控件通过撤销栈移除item。
使用撤销栈的好处是可以撤销、重做,增加了软件的可交互性,提高了容错率。
0.效果
1. 创建UI
2.实现命令
.h
class C_TreeWidgetDelCmd : public QUndoCommand
{
public:
explicit C_TreeWidgetDelCmd(QTreeWidgetItem* pCurItem,
QTreeWidgetItem* pItemParent,
int nIndex,
QUndoCommand *parent = nullptr);
virtual void redo() override;
virtual void undo() override;
signals:
private:
QTreeWidget* m_pTW;
QTreeWidgetItem* m_pCurItem;
QTreeWidgetItem* m_pItemParent;
int m_nIndex;
};
.cpp
#include "TreeWidgetOptCmd.h"
#include <QTreeWidget>
#include <QDebug>
C_TreeWidgetDelCmd::C_TreeWidgetDelCmd(QTreeWidgetItem* pCurItem,
QTreeWidgetItem* pItemParent,
int nIndex,
QUndoCommand *parent)
: QUndoCommand{parent}
, m_pCurItem(pCurItem)
, m_pItemParent(pItemParent)
, m_nIndex(nIndex)
{
m_pTW = m_pCurItem->treeWidget();
}
void C_TreeWidgetDelCmd::redo()
{
if (m_pItemParent)
{
m_pItemParent->removeChild(m_pCurItem);
}
else
{
m_pTW->takeTopLevelItem(m_nIndex);
}
m_pTW->expandAll();
}
void C_TreeWidgetDelCmd::undo()
{
if (m_pItemParent)
{
m_pItemParent->insertChild(m_nIndex, m_pCurItem);
}
else
{
m_pTW->insertTopLevelItem(m_nIndex, m_pCurItem);
}
m_pTW->expandAll();
}
3.调用
.h
#include <QMainWindow>
#include <QTreeWidgetItem>
#include <QUndoStack>
#include "TreeWidgetOptCmd.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_btn_del_clicked();
private:
Ui::MainWindow *ui;
QUndoStack* m_pUndoStack;
QAction* m_pActUndo;
QAction* m_pActRedo;
};
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pUndoStack = new QUndoStack(this);
m_pActUndo = m_pUndoStack->createUndoAction(this, tr("&Undo"));
m_pActUndo->setShortcuts(QKeySequence::Undo);
m_pActRedo = m_pUndoStack->createRedoAction(this, tr("&Redo"));
m_pActRedo->setShortcuts(QKeySequence::Redo);
ui->menubar->addAction(m_pActUndo);
ui->menubar->addAction(m_pActRedo);
connect(ui->btn_undo, &QPushButton::clicked, m_pActUndo, &QAction::trigger);
ui->treeWidget->expandAll();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btn_del_clicked()
{
QTreeWidgetItem* pCurItem = ui->treeWidget->currentItem();
QTreeWidgetItem* pItemParent = nullptr;
int nIndex = -1;
if (pCurItem)
{
pItemParent = pCurItem->parent() ? pCurItem->parent() : nullptr;
if (pItemParent)
{
nIndex = pItemParent->indexOfChild(pCurItem);
}
else
{
nIndex = ui->treeWidget->indexOfTopLevelItem(pCurItem);
}
C_TreeWidgetDelCmd* pCmd = new C_TreeWidgetDelCmd(pCurItem, pItemParent, nIndex);
m_pUndoStack->push(pCmd);
}
}
4.代码链接
【链接】https://download.csdn.net/download/MrHHHHHH/89987411