1、使用ctrl+z快捷键取消文本框修改
cpp
#include <QApplication>
#include <QLineEdit>
#include <QUndoStack>
#include <QVBoxLayout>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget window;
QVBoxLayout layout(&window);
// 创建撤销框架
QUndoStack undoStack;
// 创建文本框
QLineEdit lineEdit(&window);
layout.addWidget(&lineEdit);
// 将文本框的撤销操作绑定到撤销框架
QObject::connect(&lineEdit, &QLineEdit::textChanged, [&undoStack, &lineEdit]() {
undoStack.push(new QUndoCommand("Text Change", [&lineEdit]() {
lineEdit.setText(lineEdit.text());
}));
});
// 绑定撤销快捷键 Ctrl+Z
QShortcut *undoShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z), &window);
QObject::connect(undoShortcut, &QShortcut::activated, &undoStack, &QUndoStack::undo);
window.setLayout(&layout);
window.show();
return a.exec();
}
2、在Qt中实现文本框的复制、粘贴、剪切和回退功能;可以通过重写文本框的键盘事件来实现
cpp
#include <QtWidgets>
class MyTextEdit : public QTextEdit {
public:
MyTextEdit(QWidget *parent = nullptr) : QTextEdit(parent) {}
protected:
void keyPressEvent(QKeyEvent *event) override {
if (event->matches(QKeySequence::Copy)) {
copy();
} else if (event->matches(QKeySequence::Paste)) {
paste();
} else if (event->matches(QKeySequence::Cut)) {
cut();
} else if (event->matches(QKeySequence::Undo)) {
undo();
} else {
QTextEdit::keyPressEvent(event);
}
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyTextEdit textEdit;
textEdit.show();
return app.exec();
}