QT文本框(QTextEdit)设置内容只可复制粘贴
一、背景
今天记录一下在qt开发过程中文本框编辑模式的知识。在创建了一个窗口使用QTextEdit控件的时候,因为我的设计需求,要求在使用过程中,文本框里面的数据可被复制粘贴,但是不能被覆盖、删除、以及拖动位置。
实现设计:添加事件过滤器,选择过滤控件中的对应按键操作,从而实现该目的。
二、实现效果
通过编写事件过滤器,为textEdit控件添加上事件过滤器,从而实现不可删除剪切的目的。实现效果如图:为添加对比,本次设计创建的两个textEdit,但只为左边的控件添加了事件过滤器。
三、项目代码
1、mainwindow.h文件
// 在窗口类头文件中添加
#include <QTextEdit>
#include <QKeyEvent>class MainWindow : public QMainWindow {Q_OBJECT
public:explicit MainWindow(QWidget *parent = nullptr);protected:bool eventFilter(QObject *watched, QEvent *event) override;private:Ui::MainWindow *ui; // Designer生成的UI指针
};// 在.cpp文件中实现
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 关键:为textEdit安装事件过滤器ui->textEdit->installEventFilter(this);ui->textEdit->setContextMenuPolicy(Qt::CustomContextMenu); // 允许自定义右键菜单// 连接右键菜单信号connect(ui->textEdit, &QTextEdit::customContextMenuRequested,this, &MainWindow::onCustomContextMenu);
}
2、mainwindow.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 关键:为textEdit安装事件过滤器ui->textEdit->installEventFilter(this);ui->textEdit->setContextMenuPolicy(Qt::CustomContextMenu); // 允许自定义右键菜单
}MainWindow::~MainWindow()
{delete ui;
}
// 事件过滤逻辑
bool MainWindow::eventFilter(QObject *watched, QEvent *event) {//监听ui界面的textEdit事件,是否发生键盘按键按下的情况if (watched == ui->textEdit && event->type() == QEvent::KeyPress) {//定义按键事件指针QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);// 允许复制(Ctrl+C)和粘贴(Ctrl+V)if (keyEvent->matches(QKeySequence::Copy) || keyEvent->matches(QKeySequence::Paste))//如果是复制或者粘贴选项返回过滤器事件{return QMainWindow::eventFilter(watched, event);}// 拦截 删除、剪切、空格操作if (keyEvent->key() == Qt::Key_Delete || //删除操作keyEvent->key() == Qt::Key_Space || //空格操作keyEvent->key() == Qt::Key_Backspace || //回退操作keyEvent->matches(QKeySequence::Cut)) //剪切操作{return true; // 阻止事件}}return QMainWindow::eventFilter(watched, event);
}