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();
}
相关推荐
小郝 小郝2 分钟前
【C语言】内存函数
c语言·开发语言
cheryl8815 分钟前
Python+Requests 企业级接口测试入门(1~3天)
开发语言·python
Spring-wind19 分钟前
【golang】为什么协程开销小于线程
java·开发语言·golang
Yang-Never24 分钟前
Open GL ES -> SurfaceView + 自定义EGL实现OpenGL渲染框架
android·开发语言·图像处理·android studio
wjs202432 分钟前
Perl 发送邮件
开发语言
大刘讲IT1 小时前
构建实时、融合的湖仓一体数据分析平台:基于 Delta Lake 与 Apache Iceberg
开发语言·python·sql·mysql·数据挖掘·数据分析·json
冯韶晗2 小时前
Scala语言的区块链
开发语言·后端·golang
T - mars2 小时前
python爬虫:喜马拉雅登录案例
开发语言·python
看海的四叔3 小时前
【Python】Python 100题 分类入门练习题 - 新手友好
开发语言·python·分类·数据分析·python学习
阿猿收手吧!3 小时前
【QT】QPixmap QImage QBitmap QPicture
开发语言·c++·qt