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();
}
相关推荐
大炮走火7 分钟前
iOS在制作framework时,oc与swift混编的流程及坑点!
开发语言·ios·swift
她说彩礼65万10 分钟前
C# 容器实例生命周期
开发语言·c#
San30.18 分钟前
JavaScript 深度解析:从 map 陷阱到字符串奥秘
开发语言·javascript·ecmascript
十一.36631 分钟前
66-69 原型对象,toString(),垃圾回收
开发语言·javascript·原型模式
小小鱼儿飞3 小时前
QT音乐播放器18----新歌速递播放、隐藏顶部和底部工具栏、自定义ToolTips
开发语言·qt
穆雄雄3 小时前
Rust 程序适配 OpenHarmony 实践:以 sd 工具为例
开发语言·rust·harmonyos
0***143 小时前
Swift资源
开发语言·ios·swift
z***I3943 小时前
Swift Tips
开发语言·ios·swift
J***Q2923 小时前
Swift Solutions
开发语言·ios·swift
铅笔小新z3 小时前
C++入门指南:开启你的编程之旅
开发语言·c++