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();
}
相关推荐
·云扬·11 分钟前
【Java源码阅读系列37】深度解读Java BufferedReader 源码
java·开发语言
liulilittle41 分钟前
C++ i386/AMD64平台汇编指令对齐长度获取实现
c语言·开发语言·汇编·c++
Thomas_YXQ1 小时前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
Zz_waiting.1 小时前
Javaweb - 10.4 ServletConfig 和 ServletContext
java·开发语言·前端·servlet·servletconfig·servletcontext·域对象
Touper.2 小时前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun0077002 小时前
std::forward作用
开发语言·c++·算法
Zhen (Evan) Wang3 小时前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
虾球xz3 小时前
CppCon 2018 学习:THE MOST VALUABLE VALUES
开发语言·c++·学习
阿蒙Amon4 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
尘浮7284 小时前
60天python训练计划----day59
开发语言·python