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();
}
相关推荐
天天向上10242 分钟前
go 配置热更新
开发语言·后端·golang
晨晖217 分钟前
顺序查找:c语言
c语言·开发语言·算法
wadesir26 分钟前
C++非对称加密实战指南(从零开始掌握RSA加密算法)
开发语言·c++
SunkingYang35 分钟前
QT程序怎么接收MFC通过sendmessage发送的信号
qt·mfc·信号·事件·sendmessage·接收消息
SunkingYang1 小时前
Qt中QString 查找子串的完整指南
qt·字符串·qstring·子字符串·查找子串
a程序小傲1 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
爱装代码的小瓶子2 小时前
【c++进阶】从C++98到C++11的奇妙旅程(故事科普版)
开发语言·c++
智航GIS2 小时前
2.3 运算符详解
开发语言·python
web3.08889992 小时前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
世转神风-2 小时前
qt-在字符串中指定位置插入字符串
开发语言·qt