Qt:使用ctrl+z快捷键取消文本框修改

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();
}
相关推荐
罗曼蒂克在消亡18 分钟前
GraphQL规范
开发语言·graphql
HealthScience20 分钟前
怎么将bash(sh)的所有输出保存到log/txt中?
开发语言·bash
Word码1 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·经验分享·笔记·算法
五花肉村长1 小时前
数据结构-队列
c语言·开发语言·数据结构·算法·visualstudio·编辑器
萧鼎1 小时前
Python常见问题解答:从基础到进阶
开发语言·python·ajax
C1 小时前
C++_智能指针详解
开发语言·c++
想躺平的做题家1 小时前
Linux高级编程_29_信号
开发语言·c·信号
VBA63371 小时前
VBA数据库解决方案第十五讲:Recordset集合中单个数据的精确处理
开发语言
wrx繁星点点1 小时前
事务的四大特性(ACID)
java·开发语言·数据库
不写八个1 小时前
Python办公自动化教程(005):Word添加段落
开发语言·python·word